Skip to main content
Back to problems
#1009
Easy Algorithms

Complement of base 10 integer

Bit Manipulation
60.6% acceptance
Feb 25, 2026
2594
126
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 n, return its complement.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn bitwise_complement(n: i32) -> i32 {
    if n == 0 { return 1; }
    let mut mask = 1i32;
    while mask <= n { mask <<= 1; }
    (mask - 1) ^ n
  }
}