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 

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

你可能感兴趣的:(LeetCode,practice,for,C++,LeetCode,c++,algorithm)