LeetCode1523. Count Odd Numbers in an Interval Range

本文介绍了一个编程问题,要求在给定的两个非负整数low和high之间计算奇数的数量。提供了一种解决方案,通过考虑边界条件和调整数值使一侧变为偶数来简化计算。最后,展示了Solution类中的countOdds函数实现这一功能。
摘要由CSDN通过智能技术生成

一、题目

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].

Constraints:

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

二、题解

首先考虑两侧均是偶数的情况:奇数数量为(high - low) / 2
若左侧是奇数,则数量加一,并右移,使其变为偶数。
若右侧是奇数,则数量减一,并左移,使其变为偶数。
最终,如果左侧或右侧是奇数,可以转换为左右侧均为偶数的情况计算。

class Solution {
public:
    int countOdds(int low, int high) {
        int res = 0;
        if(low % 2 != 0){
            res++;
            low++;
        }
        if(high % 2 != 0){
            res++;
            high--;
        }
        res += (high - low) / 2;
        return res;
    }
};
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值