文章目录
- 一、题目
- 二、题解
一、题目
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
二、题解
首先考虑两侧均是偶数的情况:奇数数量为(high - low) / 2
若左侧是奇数,则数量加一,并右移,使其变为偶数。
若右侧是奇数,则数量减一,并左移,使其变为偶数。
最终,如果左侧或右侧是奇数,可以转换为左右侧均为偶数的情况计算。
class Solution {
public:int countOdds(int low, int high) {int res = 0;if(low % 2 != 0){res++;low++;}if(high % 2 != 0){res++;high--;}res += (high - low) / 2;return res;}
};