1523: 在区间范围内统计奇数数目
思路1:直接遍历
class Solution {
public:
int countOdds(int low, int high) {
int ans=0;
for(int i=low;i<=high;i++){
if(i%2==1) ans++;
}
return ans;
}
};
思路2:
- 如果两个端点都是偶数,那么奇数数目就是两者的差/2;
-
否则就是差/2+1。
class Solution {
public:
int countOdds(int low, int high) {
int ans=(high-low)/2;
if(low%2==0 && high%2==0) return ans;
else return ans+1;
}
};