十进制整数的反码。题意是给一个非负整数N的二进制表示,请你返回他的反码。例子,
Example 1:
Input: 5 Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.Example 2:
Input: 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.Example 3:
Input: 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
影子题476。这道题有好几种思路,我这里还是给出位运算的解法吧。别的解法以后有机会再补充。思路可以参加476的帖子,这里唯一需要注意的就是一个corner case N = 0,当数字为0的时候,补码是1。
时间O(1)
空间O(1)
Java实现
1 class Solution { 2 public int bitwiseComplement(int N) { 3 int sum = 0; 4 if (N == 0) return 1; 5 while (sum < N) { 6 sum = (sum << 1) | 1; 7 } 8 return sum - N; 9 } 10 }