给你两个非负整数 low
和 high
。请你返回 low
和 high
之间(包括二者)奇数的数目。
示例 1:
输入:low = 3, high = 7 输出:3 解释:3 到 7 之间奇数数字为 [3,5,7] 。
示例 2:
输入:low = 8, high = 10 输出:1 解释:8 到 10 之间奇数数字为 [9] 。
提示:
0 <= low <= high <= 10^9
方法一:前缀和思想
[0, x]
之间的奇数个数为 (x + 1) >> 1
,那么 [low, high]
之间的奇数个数为 ((high + 1) >> 1) - (low >> 1)
。
class Solution:
def countOdds(self, low: int, high: int) -> int:
return ((high + 1) >> 1) - (low >> 1)
class Solution {
public int countOdds(int low, int high) {
return ((high + 1) >> 1) - (low >> 1);
}
}
class Solution {
public:
int countOdds(int low, int high) {
return (high + 1 >> 1) - (low >> 1);
}
};
func countOdds(low int, high int) int {
return ((high + 1) >> 1) - (low >> 1)
}
function countOdds(low: number, high: number): number {
return ((high + 1) >> 1) - (low >> 1);
}
impl Solution {
pub fn count_odds(low: i32, high: i32) -> i32 {
((high + 1) >> 1) - (low >> 1)
}
}
int countOdds(int low, int high) {
return ((high + 1) >> 1) - (low >> 1);
}
class Solution {
/**
* @param Integer $low
* @param Integer $high
* @return Integer
*/
function countOdds($low, $high) {
return ($high + 1 >> 1) - ($low >> 1);
}
}