notes/OJ notes/pages/Leetcode Count-Odd-Numbers-in-an-Interval-Range.md

71 lines
1.1 KiB
Markdown
Raw Normal View History

2022-07-23 15:14:26 +08:00
# Leetcode Count-Odd-Numbers-in-an-Interval-Range
#### 2022-07-23 15:09
> ##### Algorithms:
2022-09-03 15:41:36 +08:00
>
2022-07-23 15:14:26 +08:00
> #algorithm #math
2022-09-03 15:41:36 +08:00
>
2022-07-23 15:14:26 +08:00
> ##### Difficulty:
2022-09-03 15:41:36 +08:00
>
2022-07-23 15:14:26 +08:00
> #coding_problem #difficulty-easy
2022-09-03 15:41:36 +08:00
>
2022-07-23 15:14:26 +08:00
> ##### Additional tags:
2022-09-03 15:41:36 +08:00
>
> #leetcode
>
2022-07-23 15:14:26 +08:00
> ##### Revisions:
2022-09-03 15:41:36 +08:00
>
2022-07-23 15:14:26 +08:00
> N/A
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-07-23 15:14:26 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-07-23 15:28:38 +08:00
- [Link to problem](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/)
2022-09-03 15:41:36 +08:00
---
2022-07-23 15:14:26 +08:00
### Problem
2022-09-03 15:41:36 +08:00
Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` *(inclusive)*.
2022-07-23 15:28:38 +08:00
2022-07-23 15:14:26 +08:00
#### Examples
2022-07-23 15:28:38 +08:00
**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].
2022-07-23 15:14:26 +08:00
#### Constraints
2022-09-03 15:41:36 +08:00
- `0 <= low <= high <= 10^9`
2022-07-23 15:28:38 +08:00
2022-07-23 15:14:26 +08:00
### Thoughts
> [!summary]
2022-07-23 15:28:38 +08:00
> This is a #math problem.
The problem is intended to be solved with math.
The key to find the solution is by analyzing and find common
rules.
2022-07-23 15:14:26 +08:00
### Solution
2022-07-23 15:28:38 +08:00
```cpp
class Solution {
public:
int countOdds(int low, int high) {
return ((low % 2) | (high % 2)) + (high - low) / 2;
}
};
2022-09-03 15:41:36 +08:00
```