leetcode 1523. Count Odd Numbers in an Interval Range(python)

511 阅读1分钟

描述

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:

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

解析

根据题意,就是找出包含 high 和 low 在内的范围的所有奇数,多找一些例子就会发现规律,当 high 和 low 都是偶数的时候,结果为 high//2 - low//2 ,其他情况都是 (high-low)//2+1 。

解答

class Solution(object):
    def countOdds(self, low, high):
        """
        :type low: int
        :type high: int
        :rtype: int
        """
        if low%2==0 and high%2==0:
            return high//2 - low//2
        else:
            return (high-low)//2+1          	      
		

运行结果

Runtime: 12 ms, faster than 95.28% of Python online submissions for Count Odd Numbers in an Interval Range.
Memory Usage: 13.3 MB, less than 88.98% of Python online submissions for Count Odd Numbers in an Interval Range.

原题链接:leetcode.com/problems/co…

您的支持是我最大的动力