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

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

思路:

①遍历(low,high+1),若num%2!=0,则值+1,最后return结果

②如果low为奇数,则个数为(high-low)//2+1;如果low为偶数,则个数为(high-low-1)//2-1

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

③因为①思路中,若范围较大时会超出运行时间。又因为区间[0,x]的奇数个数=(x+)//2,所以范围为[low,high]的奇数个数就会等于[0,high]的奇数个数-[0,low-1]的奇数个数

class Solution:
    def countOdds(self, low: int, high: int) -> int:
        pre = lambda x: (x + 1) >> 1
        return pre(high) - pre(low - 1)
'''
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/count-odd-numbers-in-an-interval-range/solution/zai-qu-jian-fan-wei-nei-tong-ji-qi-shu-shu-mu-by-l/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
'''
posted @ 2022-05-10 19:45  吴呀呀~  阅读(111)  评论(0)    收藏  举报