1523. Count Odd Numbers in an Interval Range

The description of problem

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-odd-numbers-in-an-interval-range.

The naive solution

intuition: traverse all elements and pick up elements satisfing requirement.

The solution use pre-condition summarization

intuition: we could easily get the odds number in the range from an integer number to 0.

The solution use the even and odd number is about even, which could be described by the following equestions:

( h i g h − l o w + 1 ) / 2 (high - low +1) / 2 (highlow+1)/2

Nevertheless, there is an exception that when the high and low interger are both odd. The above equation should be rewritten as followings:

( h i g h − l o w + 1 ) / 2 + 1 (high - low +1) / 2 + 1 (highlow+1)/2+1

The codes corresponding to above all solutions:

#include <iostream>

class Solution {
public:
    //the naive solution traversing all elements in the range [l, r]
    int countOddsNaive(int low, int high) {
        int count = 0;
        for (int i = low; i <= high; i++) {
            if (i % 2 == 1) {
                count++;
            }
        }
        return count;
    }
    //the solution utilize the property of odd numbers (pre-condition summation)
    int pre(int x){
        return (x + 1) >> 1;
    }
    int countOddsPre(int low, int high){
        return pre(high) - pre(low - 1);
    }
    //the solution utilize the property of odd numbers (middle-condition summation)
    int countOdds(int low, int high) {
      if ((low % 2 != 0)&&(high % 2 != 0)){
        return (high - low + 1) / 2 +1;
      }
        return (high - low + 1) / 2;
     
    }
};

int main()
{
   //test Solution
    Solution s;
    std::cout << s.countOdds(1, 7) << std::endl;
    std::cout << s.countOddsNaive(1, 7) << std::endl;
    std::cout << s.countOddsPre(1, 7) << std::endl;
    return 0;
}

results corresponding to above codes:

The results from middle condition minus: 4
The results from naive condition: 4
The results from pre-condition summation:4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值