[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 = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

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

Note:

  1. 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)

上一篇:P4747 [CERC2017]Intrinsic Interval


下一篇:服务器批量健康检测(ansible+python+shell)