1523.在區間範圍內統計奇數數目
阿新 • • 發佈:2022-05-10
題目:給你兩個非負整數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) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。'''