题目链接:1523. 在区间范围内统计奇数数目 - 力扣(LeetCode)

题目描述:

返回low与high之间的奇数数目,如果直接用for循环遍历来数的话,效率就慢了。可以直接通过公式计算数目,复杂度为

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int countOdds(int low, int high) {
if (low % 2 == 0)
low += 1;
if (high % 2 == 0)
high -= 1;
if (low > high)
return 0;
return (high - low + 1) / 2 + 1;
}
};

评测结果: