Skip to content

Latest commit

 

History

History
100 lines (67 loc) · 2.05 KB

File metadata and controls

100 lines (67 loc) · 2.05 KB

English Version

题目描述

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

Python3

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        return ((high + 1) >> 1) - (low >> 1)

Java

class Solution {
    public int countOdds(int low, int high) {
        return ((high + 1) >> 1) - (low >> 1);
    }
}

Rust

impl Solution {
    pub fn count_odds(low: i32, high: i32) -> i32 {
        ((high + 1) >> 1) - (low >> 1)
    }
}

C++

class Solution {
public:
    int countOdds(int low, int high) {
        return (high + 1 >> 1) - (low >> 1);
    }
};

Go

func countOdds(low int, high int) int {
	return ((high + 1) >> 1) - (low >> 1)
}

...