LeetCode problem#1009
Complement of Base 10 Integer
Solved in 1 languageJava
Solution
19 lines
1class Solution {
2 public int bitwiseComplement(int n) {
3 if (n == 0) {
4 return 1;
5 }
6
7 int i = 30;
8 while (i >= 0) {
9 int bit = n & (1 << i);
10 if (bit > 0) {
11 break;
12 }
13 i--;
14 }
15
16 int mask = (1 << i + 1) - 1;
17 return ~n & mask;
18 }
19}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.