Leetcode-1523. 在区间范围内统计奇数数目

题目:

给你两个非负整数 low 和 high 。请你返回 low  high 之间(包括二者)奇数的数目。

示例 1:

输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。

示例 2:

输入:low = 8, high = 10
输出:1
解释:8 到 10 之间奇数数字为 [9] 。

提示:

  • 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;}
}