题目
Every non-negative integer N has a binary representation. For example, 5 can be represented as “101” in binary, 11 as “1011” in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.
The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of “101” in binary is “010” in binary.
For a given number N in base-10, return the complement of it’s binary representation as a base-10 integer.
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.
Note:
0 <= N < 10^9
This question is the same as 476: https://leetcode.com/problems/number-complement/
思路
考虑到complement加起来是 111...111 111...111 111...111,所以先计算位数然后在做差;input为0的时候有特例,因为是1位但是计算结果会是0位所以需要特殊处理。代码如下。
class Solution {
public int bitwiseComplement(int N) {
if (N == 0) return 1;
int len = 0, temp = N;
while (temp != 0) {
temp /= 2;
len++;
}
int mask = 0;
for (int i = 0; i < len; i++) {
mask = (mask << 1) + 1;
}
return mask - N;
}
}
也可以考虑在计算位数的时候同时生成
111...111
111...111
111...111的mask,mask每一位都左移1再加上1mask = (mask << 1) | 1
,位数不足时有(mask & N) != N
。同时位运算的速度要优于普通代数运算,又因为java的~运算符本身提供01取反的功能,左侧会补齐符号位,所以我们只要用mask去取非符号位即可。代码如下
class Solution {
public int bitwiseComplement(int N) {
int mask = 1;
while((mask & N) != N) {
mask = (mask << 1) | 1;
}
return (~N) & mask;
}
}