[LeetCode] 1009. Complement of Base 10 Integer 十进制整数的补码


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:

  1. 0 <= N < 10^9
  2. This question is the same as 476: https://leetcode.com/problems/number-complement/

这道题让求十进制整数的补码,我们都知道补码是二进制中的一个概念,就是每一位上的数都跟原数是相反的,这里所谓的十进制的补码,其实就是先转为二进制,再求补码,再转回十进制数。既然是求补码,最直接的方法就是从低到高,一位一位的取出来,然后进行取反。对于一个十进制数取其二进制数的最低位的方法,就是‘与’上一个1,然后取反,取反就是‘异或’上一个1,接着就是左移对应的位数,可以用一个变量i来统计当前处理到第几位了,然后直接左移i位就行了。之后N要右移一位,i自增1即可,参见代码如下:


解法一:

class Solution {
public:
    int bitwiseComplement(int N) {
        if (N == 0) return 1;
		int res = 0, i = 0;
		while (N > 0) {
			res += ((N & 1) ^ 1) << i;
			N >>= 1;
			++i;
		}
		return res;
    }
};

我们也可以使用一个 for 循环,这样可以写的更简洁一些,思路都是完全一样的,参见代码如下:


解法二:

class Solution {
public:
    int bitwiseComplement(int N) {
        if (N == 0) return 1;
		int res = 0, i = 0;
		for (int i = 0; N > 0; ++i, N >>= 1) {
			res += ((N & 1) ^ 1) << i;
		}
		return res;
    }
};

下面的这种解法用到了一些补码的性质,那就是一个二进制数加上其补码,则每个位置上都会变成1,且位数和原数相同。这样的话我们就可以先求出这个各位上全是1的数,然后再做减法,就可以得到补码了,参见代码如下:


解法三:

class Solution {
public:
    int bitwiseComplement(int N) {
        int X = 1;
        while (N > X) X = X * 2 + 1;
        return X - N;
    }
};

由于‘异或’的特点,在求得了各位上都是1的数字后,直接‘异或’上原数,也可以得到补码,参见代码如下:


解法四:

class Solution {
public:
    int bitwiseComplement(int N) {
        int X = 1;
        while (N > X) X = X * 2 + 1;
        return X ^ N;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1009


参考资料:

https://leetcode.com/problems/complement-of-base-10-integer/

https://leetcode.com/problems/complement-of-base-10-integer/discuss/256740/JavaC%2B%2BPython-Find-111.....1111-greater-N

https://leetcode.com/problems/complement-of-base-10-integer/discuss/613118/4-approaches%3A-bitwise-operation-math-formular-one-naive-simulation-and-bonus


LeetCode All in One 题目讲解汇总(持续更新中...)

上一篇:[bzoj3569]DZY Loves Chinese II


下一篇:UNI-APP,plus.runtime.openURL打开手机自带浏览器,出现“下载地址不可用,创建任务失败”的Bug