#1611
Hard Algorithms Minimum one bit operations to make integers zero
Math Dynamic Programming Bit Manipulation Recursion Memoization
78.5% acceptance
Feb 25, 2026
1206
1204
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_one_bit_operations(n: i32) -> i32 {
// This is equivalent to converting n from Gray code to binary (canonical inverse Gray code)
let mut n = n;
let mut res = 0;
while n > 0 {
res ^= n;
n >>= 1;
}
res
}
}