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].
给两个非负整数low 和 high, 找出[low, high]区间内奇数的个数。
思路:
感觉这个纯靠观察,
举个例子:
case 1: low和high都是奇数, (high - low)是偶数,其中有一半是奇数, 另外要加上边界的奇数
1 2 3 4 5
在(5-1)个数字1,2,3,4中,奇数的个数是一半,也就是(5-1)/2,
但是high = 5, 本身也是个奇数,所以最后是(5-1)/2+1
case 2:low和high有一个是奇数,(high - low)也是奇数,算出来的是不包含边界部分的奇数个数
1 2 3 4
在(4-1)个数字2,3,4中,奇数的个数是(4-1)/2 = 1
但是low=1,本身是奇数,所以最后是(4-1)/2+1
2 3 4 5
在(5-2)个数字2,3,4中,奇数的个数是(5-2)/2 = 1
但是high=5是奇数,最后是(5-2)/2+1
case 3:
low和high都是偶数,
2 3 4 5 6
在(6-2)个数字2,3,4,5中,有一半是奇数,也就是(6-2)/2
总结,low和high都是偶数时,奇数个数为(high-low)/2
low和high中有一个是奇数或都是奇数时,奇数个数为(high-low)/2+1
判断奇数不需要用(low % 2 != 0), 可以用(low & 1 != 0)
public int countOdds(int low, int high) {
int res = (high - low) / 2;
if((low & 1) != 0 || (high & 1) != 0) res ++;
return res;
}