Skip to content

1009. Complement of Base 10 Integer 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int bitwiseComplement(int n) {
    int mask = 1;
    while (mask < n)
      mask = (mask << 1) + 1;
    return mask ^ n;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public int bitwiseComplement(int n) {
    int mask = 1;
    while (mask < n)
      mask = (mask << 1) + 1;
    return mask ^ n;
  }
}
1
2
3
4
5
6
class Solution:
  def bitwiseComplement(self, n: int) -> int:
    mask = 1
    while mask < n:
      mask = (mask << 1) + 1
    return mask ^ n