Input: n =2 Output:10 Explanation: The smallest fair integer that is greater than or equal to 2is10.10is fair because it has an equal number of even and odd digits(one odd digit and one even digit).
Example 2:
1
2
3
4
Input: n =403 Output:1001 Explanation: The smallest fair integer that is greater than or equal to 403is1001.1001is fair because it has an equal number of odd and even digits(two odd digits and two even digits).
A fair integer has an equal number of even and odd digits. Since the constraint is small, we can check each number starting from n and return the first fair integer we find.
classSolution {
public:int closestFair(int n) {
for (int x = n; ; ++x) {
int even =0, odd =0, t = x;
while (t) {
if ((t %10) %2==0) even++;
else odd++;
t /=10;
}
if (even == odd) return x;
}
}
};
classSolution {
publicintclosestFair(int n) {
for (int x = n; ; x++) {
int even = 0, odd = 0, t = x;
while (t > 0) {
if ((t % 10) % 2 == 0) even++;
else odd++;
t /= 10;
}
if (even == odd) return x;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funclosestFair(n: Int): Int {
var x = n
while (true) {
var even = 0; var odd = 0; var t = x
while (t > 0) {
if ((t % 10) % 2==0) even++else odd++ t /=10 }
if (even == odd) return x
x++ }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defclosestFair(self, n: int) -> int:
x = n
whileTrue:
even = odd =0 t = x
while t >0:
if (t %10) %2==0:
even +=1else:
odd +=1 t //=10if even == odd:
return x
x +=1