今天在sublime盲写了一下generate parentheses ,一次AC了,开心。
我发现easy题就像有人说的,是「阅读理解」,按照它描述的做就行了。但是,这种题目往往有非常简短的解法。
下面我写得很长。
public int findComplement(int num) {
String originBinary = Integer.toBinaryString(num);
String flippedBinary = "";
for (int i = 0; i < originBinary.length(); i++) {
flippedBinary += originBinary.charAt(i) == '1' ? 0 : 1;
}
int count = 0;
while (count < flippedBinary.length() && flippedBinary.charAt(count) == '0') {
count++;
}
flippedBinary = flippedBinary.substring(count, flippedBinary.length());
int res = 0;
for (int i = 0; i < flippedBinary.length(); i++) {
res += (flippedBinary.charAt(flippedBinary.length() - 1 - i) == '0' ? 0 : 1) * Math.pow(2, i);
}
return res;
}
炫酷的bit manipulation
一行搞定,会bit操作真的很炫酷。
https://leetcode.com/problems/number-complement/#/solutions
public class Solution {
public int findComplement(int num) {
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
}
}
新颖做法
这个解法挺有意思的,原码和complement相加的binary一定是11111..这种形式,就比如说5 + 2 = 7, 1 +0 = 1,那么找到7,减去5,答案就是2了。
public int findComplement(int num)
{
int i = 0;
int j = 0;
while (i < num)
{
i += Math.pow(2, j);
j++;
}
return i - num;
}