2417. Closest Fair Integer π
Description
You are given a positive integer n
.
We call an integer k
fair if the number of even digits in k
is equal to the number of odd digits in it.
Return the smallest fair integer that is greater than or equal to n
.
Example 1:
Input: n = 2 Output: 10 Explanation: The smallest fair integer that is greater than or equal to 2 is 10. 10 is fair because it has an equal number of even and odd digits (one odd digit and one even digit).
Example 2:
Input: n = 403 Output: 1001 Explanation: The smallest fair integer that is greater than or equal to 403 is 1001. 1001 is fair because it has an equal number of even and odd digits (two odd digits and two even digits).
Constraints:
1 <= n <= 109
Solutions
Solution 1: Case Discussion
We denote the number of digits of $n$ as $k$, and the number of odd and even digits as $a$ and $b$ respectively.
- If $a = b$, then $n$ itself is
fair
, and we can directly return $n$; - Otherwise, if $k$ is odd, we can find the smallest
fair
number with $k+1$ digits, in the form of10000111
. If $k$ is even, we can directly brute forceclosestFair(n+1)
.
The time complexity is $O(\sqrt{n} \times \log_{10} n)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|