[Python] [leetcode]-1523:Count Odd Numbers in an Interval Range

Question:

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

Example:

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

Constraints: 

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

题意:

求在区间内[low,high]中奇数的个数。

难度:

Easy 

解题思路:

步骤1:观察区间内个数

[ 3 , 7] : 3, 4, 5, 6, 7

计算范围 7 - 3 = 4 代表头尾有1数不含,而4%2 = 0代表奇偶各半

p.s. 如果区间范围为奇数,则代表一定有相对数量的奇数

因此

步骤2:观察头尾是否有1数为奇数,如果是,则ans加1

程式码:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值