Skip to content

Latest commit

 

History

History
131 lines (92 loc) · 2.5 KB

File metadata and controls

131 lines (92 loc) · 2.5 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);
    }
}

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)
}

TypeScript

function countOdds(low: number, high: number): number {
    return ((high + 1) >> 1) - (low >> 1);
}

Rust

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

C

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

PHP

class Solution {
    /**
     * @param Integer $low
     * @param Integer $high
     * @return Integer
     */
    function countOdds($low, $high) {
        return ($high + 1 >> 1) - ($low >> 1);
    }
}

...