본문 바로가기
python-algorithm

leetcode 1523. Count Odd Numbers in an Interval Range

by 무적김두칠 2023. 2. 13.

https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/

 

Count Odd Numbers in an Interval Range - LeetCode

Can you solve this real interview question? Count Odd Numbers in an Interval Range - Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).   Example 1: Input: low = 3, high = 7 Output: 3 Explanati

leetcode.com

 

1
2
3
4
5
6
7
8
class Solution:
    def countOdds(self, low: int, high: int-> int:
        if low%2 == 0 and high % 2 == 0 : 
            answer = (high-low)//2
        else:
            answer = (high-low)//2 + 1
 
        return answer
cs

사실 이 문제는 공학적으로 생각하기보단.. 수학(정수론) 적으로 생각하면 되게 쉽게 풀려요

low와 high가 둘다 짝수일 때와 아닐경우 생각해보세요!

In fact, this problem is solved very easily if you think mathematically (number theory) rather than engineering.
Think about when low and high are both even and when they are not!

반응형

댓글