I am writing a leetCode question where ask me to output a integer's complement integer. LeetCode#476
I always thought bit manipulation is fast because in the very end, everything is done by bit manipulation. But in this problem, a string method is faster than bit manipulation and I am wondering why.
I wrote a string operation code which is accepted in 11ms. The code is following, very intuitive.
class Solution {
public int findComplement(int num) {
String s = Integer.toBinaryString(num);
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()){
sb.append(c == '1' ? 0 : 1);
}
int ret = Integer.parseInt(sb.toString(), 2);
return ret;
}
}
I peeked through the discussions and found a bit operation to solve the problem and I tried it. However, it was accepted with 13ms. Below is the code.
class Solution {
public int findComplement(int num) {
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
}
}