Problem
Solutions (time, space)
- bit calculation with JAVA method
- bit calculation with bitwise operator
I solved with JAVA method. But, this problem is asking, "Do you know bitwise? Do you know how computer save data?"
bit calculation with JAVA method O(n), O(n)
class Solution {
public int bitwiseComplement(int n) {
String base2String = Integer.toBinaryString(n);
StringBuilder sb = new StringBuilder(base2String.length());
for (char tempChar : base2String.toCharArray()) {
int tempInt = (tempChar == '1') ? 0 : 1;
sb.append(tempInt);
}
return Integer.parseInt(sb.toString(), 2);
}
}
Explanation
- get base 2 String from input int base 10
- reverse the base 2 String by StringBuilder
- get base 10 in from reversed base 2 String
bit calculation with bitwise operator O(n), O(1)
class Solution {
public int bitwiseComplement(int n) {
int bitCounter = n;
int tempBit = 0;
if (n==0) return 1;
while (bitCounter != 0) {
tempBit = (tempBit << 1) | 1;
bitCounter = bitCounter >> 1;
}
return (~n & tempBit);
}
}
Explanation
- ~10 (NOT gate of n) = 1111 1111 1111 1111 1111 1111 1111 0101 (because of Java using 32 bits)
- ~10 & 1111 = the answer=0101
- to get 1111, move bit to left and add 1 only length what we wanted.
- bitCounter : the length of bits for input
- tempBit : added 1 as length
while (bitCounter != 0) { tempBit = (tempBit << 1) | 1; bitCounter = bitCounter >> 1; }