LeetCode 1523. Count Odd Numbers in an Interval Range
LeetCode 1523. Count Odd Numbers in an Interval Range (在区间范围内统计奇数数目)
题目
链接
https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range/
问题描述
给你两个非负整数 low 和 high 。请你返回 low 和 high 之间(包括二者)奇数的数目。
示例
输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。
提示
0 <= low <= high <= 10^9
思路
只需要除法计算一下就行了,同时要考虑到两端,有奇数的话结果加一。
复杂度分析
时间复杂度 O(1)
空间复杂度 O(1)
代码
Java
public int countOdds(int low, int high) {
int ans = (high - low) >> 1;
int x = low % 10;
int y = high % 10;
if (x % 2 == 1||y % 2 == 1) {
ans++;
}
return ans;
}