[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.

十进制整数的反码。题意是给一个非负整数N的二进制表示,请你返回他的反码。影子题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 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12830488.html