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!
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 989. Add to Array-Form of Integer (0) | 2023.02.15 |
---|---|
leetcode 21. Merge Two Sorted Lists (0) | 2023.02.13 |
leetcode 234. Palindrome Linked List (0) | 2023.02.11 |
leetcode 121. Best Time to Buy and Sell Stock (0) | 2023.02.11 |
leetcode 2149. Rearrange Array Elements by Sign (0) | 2023.02.10 |
댓글