LeetCode1523- Count Odd Numbers in an Interval Range (Easy)
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 Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9].
方法:Math
Time complexity: O(1) Space complexity: O(1)
class Solution: def countOdds(self, low: int, high: int) -> int: # low: odd && high: odd [3,9] 3, 5, 7,9 count = 0 if low % 2 == 1 and high %2 == 1: count = self.getNum(low, high) elif low % 2 == 1 and high % 2 == 0: #[3, 8] high -= 1 count = self.getNum(low, high) elif low %2 == 0 and high % 2 == 1: #[4, 7] low += 1 count = self.getNum(low, high) else: low += 1 high -= 1 count = self.getNum(low, high) return count def getNum(self, low, high): count = (high - low -1) //2 + 2 return count
浙公网安备 33010602011771号