forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumber Complement.java
More file actions
38 lines (34 loc) · 962 Bytes
/
Number Complement.java
File metadata and controls
38 lines (34 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public int findComplement(int num) {
return getDecimalVal(flip(getBinaryVal(num)));
}
public String getBinaryVal(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
sb.append(String.valueOf(n%2));
n /= 2;
}
return sb.reverse().toString();
}
public String flip(String s) {
StringBuilder sb = new StringBuilder();
for (int i=0;i<s.length();i++) {
if (s.charAt(i) == '1') {
sb.append("0");
}
else {
sb.append("1");
}
}
return sb.reverse().toString();
}
public int getDecimalVal(String s) {
int n = 0;
for (int i=0;i<s.length();i++) {
int mul = (int)Math.pow(2, i);
int num = Integer.parseInt(String.valueOf(s.charAt(i)));
n += mul*num;
}
return n;
}
}