Likou 1523. Count Odd Numbers in an Interval Range

Title description

Give you two non-negative integers low and high. Please return the odd number between low and high (including both).

Example

示例 1:

输入:low = 3, high = 7
输出:3
解释:3 到 7 之间奇数数字为 [3,5,7] 。

示例 2:

输入:low = 8, high = 10
输出:1
解释:8 到 10 之间奇数数字为 [9] 。

prompt

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

Problem solving ideas

The direct traversal of this question will overtime
check the prompts and find that you can find the relationship between consecutive numbers and odd numbers in the interval. Since 0 starts even and odd numbers appear in turn, when high-low+1 is even, the boundary is one odd and one even, when the boundaries are all When the number is even or odd, high-low+1 is an odd number. At this time, discuss: if all are even numbers, the number of odd numbers in the interval is (int)high-low/2; if all numbers are odd, the number of odd numbers in the interval is high-low/2+1;

Code

int countOdds(int low, int high){
    
    
    int count=high-low+1;
    if(count%2==0)return count/2;
    else if (high%2==0)return (int)count/2;
    else return (int)count/2+1;
}

link

Guess you like

Origin blog.csdn.net/qq_44722674/article/details/112172338