#476
Easy Algorithms Number complement
Bit Manipulation
70.4% acceptance
Jan 13, 2026
3205
144
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer num, return its complement.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn find_complement(num: i32) -> i32 {
let bits = 32 - num.leading_zeros();
let mask = (1 << bits) - 1;
num ^ mask
}
}