Skip to content

Commit 93f9510

Browse files
authoredMar 28, 2017
Create 476. Number Complement.java
1 parent fdbaa1a commit 93f9510

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
 

Diff for: ‎476. Number Complement.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// https://leetcode.com/problems/number-complement
2+
3+
public class Solution {
4+
public int highestBit(int num) {
5+
int pos = 0;
6+
while (num != 0) {
7+
pos++;
8+
num >>= 1;
9+
}
10+
return pos;
11+
}
12+
13+
public int findComplement(int num) {
14+
int highest = highestBit(num);
15+
int ones = 0;
16+
17+
for (int i = 1; i <= highest; i++) {
18+
ones = (ones << 1) | 1;
19+
}
20+
21+
return ones ^ num;
22+
}
23+
}

0 commit comments

Comments
 (0)
Please sign in to comment.