Question:
Given two non-negative integers low
and high
. Return the count of odd numbers between low
and high
(inclusive).
Example:
Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7].
Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
题意:
求在区间内[low,high]中奇数的个数。
难度:
Easy
解题思路:
步骤1:观察区间内个数
[ 3 , 7] : 3, 4, 5, 6, 7
计算范围 7 - 3 = 4 代表头尾有1数不含,而4%2 = 0代表奇偶各半
p.s. 如果区间范围为奇数,则代表一定有相对数量的奇数
因此
步骤2:观察头尾是否有1数为奇数,如果是,则ans加1
程式码:
class Solution(object):
def countOdds(self, low, high):
"""
:type low: int
:type high: int
:rtype: int
:type ans: int
"""
if (low % 2 | high % 2) == 1 :
ans = (high-low) / 2 +1
else :
ans = (high-low)/ 2
return ans