Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

 

Example 1:

Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:

Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
 

Constraints:

0 <= low <= high <= 10^9

这题可以硬破,但是那也太没意思了。我们可以找下规律,可以发现最终的结果,等于两个数字之间所有数字的个数除以2,然后看看首尾两个是否为奇数,假设是奇数再加一。

假设个数是偶数,那么直接除以二即可,因为两两相交,肯定是1奇1偶的次数出现的。


class CountOddNumbersInAnIntervalRange : public Solution {
public:
    void Exec() {

    }
    int countOdds(int low, int high) {
        int diff = high - low + 1;
        int res = diff / 2;
        if (diff % 2 != 0 && ((low) % 2 != 0 || (high) % 2 != 0)) {
            ++res;
        }
        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day