Leetcode 1523. Count Odd Numbers in an Interval Range
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Q: Are the low and high values inclusive?
A: Yes, both low and high are inclusive.
Q: Can low be greater than high?
A: No, it is stated that low and high are non-negative integers and typically low will be less than or equal to high.
Q: What is the expected range of values for low and high?
A: The values can be anywhere from 0 to (10^9).
n is odd if n % 2 != 0.low and high are even.low and high are odd.low and high.low and high which is (high - low + 1).low or high is odd since the inclusive range includes an additional odd number.(high - low + 1) // 2.low or high is odd, add 1 to the base count.public class Solution {
public int countOdds(int low, int high) {
// Step 1: Count the total numbers in the range
int totalNumbers = high - low + 1;
// Step 2: Calculate the number of odd numbers
int oddCount = totalNumbers / 2;
// Step 3: Check if either low or high is odd
if (low % 2 != 0 || high % 2 != 0) {
oddCount++;
}
return oddCount;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?