Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
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^9Problem summary: Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
3 7
8 10
check-if-bitwise-or-has-trailing-zeros)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1523: Count Odd Numbers in an Interval Range
class Solution {
public int countOdds(int low, int high) {
return ((high + 1) >> 1) - (low >> 1);
}
}
// Accepted solution for LeetCode #1523: Count Odd Numbers in an Interval Range
func countOdds(low int, high int) int {
return ((high + 1) >> 1) - (low >> 1)
}
# Accepted solution for LeetCode #1523: Count Odd Numbers in an Interval Range
class Solution:
def countOdds(self, low: int, high: int) -> int:
return ((high + 1) >> 1) - (low >> 1)
// Accepted solution for LeetCode #1523: Count Odd Numbers in an Interval Range
impl Solution {
pub fn count_odds(low: i32, high: i32) -> i32 {
((high + 1) >> 1) - (low >> 1)
}
}
// Accepted solution for LeetCode #1523: Count Odd Numbers in an Interval Range
function countOdds(low: number, high: number): number {
return ((high + 1) >> 1) - (low >> 1);
}
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.