LeetCode 1523:统计某个区间的奇数个数 - 示例:低值 8,高值 10,结果 1(答案:区间内的奇数是 9)
最编程
2024-02-18 07:00:33
...
0 <= low <= high <= 10^9
第一种方法,直接判断奇数偶数,是奇数,计数器++;
class Solution {
public int countOdds(int low, int high) {
int cnt = 0;
if(low%2!=0){
while(low<=high){
cnt++;
low+=2;
}
}
if(low%2==0){
low++;
while(low<=high){
cnt++;
low+=2;
}
}
return cnt;
}
}
第二种,列出所有情况,high-low=0;low奇,high偶;high奇,low偶;low、high全奇全偶。
class Solution {
public int countOdds(int low, int high) {
int cnt = 0;
if(high-low==0){
if(low%2==0)return cnt;
return cnt+1;
}
if(low%2==0&&high%2==0){
cnt+=(high-low)/2;
}else if(low%2!=0&&high%2!=0){
cnt+=((high-low)/2+1);
}else{
cnt+=(high-low+1)/2;
}
return cnt;
}
}
第三种,一行代码秒杀!
class Solution {
public int countOdds(int low, int high) {
return (high+1)/2 - low/2;
}
}
上一篇: 轻松实现 EasyUI 组件的动态加载
下一篇: ES实战-聚集