跳转至

1523. 在区间范围内统计奇数数目

题目描述

给你两个非负整数 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)

1
2
3
class Solution:
    def countOdds(self, low: int, high: int) -> int:
        return ((high + 1) >> 1) - (low >> 1)
1
2
3
4
5
class Solution {
    public int countOdds(int low, int high) {
        return ((high + 1) >> 1) - (low >> 1);
    }
}
1
2
3
4
5
6
class Solution {
public:
    int countOdds(int low, int high) {
        return (high + 1 >> 1) - (low >> 1);
    }
};
1
2
3
func countOdds(low int, high int) int {
    return ((high + 1) >> 1) - (low >> 1)
}
1
2
3
function countOdds(low: number, high: number): number {
    return ((high + 1) >> 1) - (low >> 1);
}
1
2
3
4
5
impl Solution {
    pub fn count_odds(low: i32, high: i32) -> i32 {
        ((high + 1) >> 1) - (low >> 1)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    /**
     * @param Integer $low
     * @param Integer $high
     * @return Integer
     */
    function countOdds($low, $high) {
        return ($high + 1 >> 1) - ($low >> 1);
    }
}
1
2
3
int countOdds(int low, int high) {
    return ((high + 1) >> 1) - (low >> 1);
}

评论