#2417
Medium Algorithms Closest fair integer
Math Enumeration
44.3% acceptance
Mar 31, 2026
29
13
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn closest_fair(n: i32) -> i32 {
let mut x = n;
loop {
let mut odd = 0;
let mut even = 0;
let mut tmp = x;
while tmp > 0 {
if (tmp % 10) % 2 == 0 { even += 1; } else { odd += 1; }
tmp /= 10;
}
if odd == even { return x; }
// If digit count is odd, skip to next even-digit number
let digits = (odd + even) as u32;
if digits % 2 == 1 {
// smallest (digits+1)-digit number with equal odd/even
// digits+1 is even. Half odd, half even. "10...0" with (digits+1) digits
x = 10_i32.pow(digits);
continue;
}
x += 1;
}
}
}