1523. Count Odd Numbers in an Interval Range #2506
-
|
Topics: Given two non-negative integers Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We are given two non-negative integers low and high. We need to count the number of odd numbers between low and high (inclusive). The straightforward way is to iterate from low to high and count the odd numbers. However, this would be O(n) and might be too slow for large inputs (up to 10⁹). Therefore, we need a mathematical approach. Approach:
Let's implement this solution in PHP: 1523. Count Odd Numbers in an Interval Range <?php
/**
* @param Integer $low
* @param Integer $high
* @return Integer
*/
function countOdds($low, $high) {
// Count odds from 0 to high minus odds from 0 to low-1
$countToHigh = (int)(($high + 1) / 2);
$countToLowMinusOne = (int)($low / 2);
return $countToHigh - $countToLowMinusOne;
}
// Test cases
echo countOdds(3, 7) . "\n"; // Output: 3
echo countOdds(8, 10) . "\n"; // Output: 1
?>Explanation:
Time Complexity: O(1) |
Beta Was this translation helpful? Give feedback.
We are given two non-negative integers low and high. We need to count the number of odd numbers between low and high (inclusive).
The straightforward way is to iterate from low to high and count the odd numbers. However, this would be O(n) and might be too slow for large inputs (up to 10⁹). Therefore, we need a mathematical approach.
Approach:
highusing integer division:(high + 1) // 2low - 1using integer division:low // 2[low, high]Let's implement this solution in PHP: 1523. Count Odd Numbers in an Inte…