[leetcode] 1523. Count Odd Numbers in an Interval Range

网友投稿 1180 2022-08-23

[leetcode] 1523. Count Odd Numbers in an Interval Range

[leetcode] 1523. Count Odd Numbers in an Interval Range

Description

Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).

Example 1:

Input: low = 3, high = 7Output: 3Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10Output: 1Explanation: The odd numbers between 8 and 10 are [9].

Note:

0 <= low <= high <= 10^9.

分析

题目的意思是:求出给定区间[low,high]中奇数的个数。思路很直接,我把low和high的奇偶性单独拿出来判断,剩下的按照奇偶各一半的思路,直接求出来就行了。

我看了一下别人的解法,直接判断从1开始以low和hight结尾的奇数个数,然后相减就行了,思路很好。(high + 1) / 2 - low / 2

代码

class Solution: def countOdds(self, low: int, high: int) -> int: res=0 if(low%2==1): low+=1 res+=1 if(high%2==1): high-=1 res+=1 res+=(high-low)//2 return res

参考文献

[Java/C++/Python] 1-Lines](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/discuss/754726/JavaC%2B%2BPython-1-Lines)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C语言编程时常犯的18种错误(c语言编程常见错误例题)
下一篇:[leetcode] 1685. Sum of Absolute Differences in a Sorted Array
相关文章

 发表评论

暂时没有评论,来抢沙发吧~