1009.Complement of Base 10 Integer(十进制整数的补码)

Description

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.


每个非负整数 N 都有其二进制表示。例如, 5 可以被表示为二进制 "101"11 可以用二进制 "1011" 表示,依此类推。注意,除 N = 0 外,任何二进制表示中都不含前导零。

二进制的补码表示是将每个 1 改为 0 且每个 0 变为 1。例如,二进制数 "101" 的二进制补码为 "010"

给定十进制数 N,返回其二进制表示的补码所对应的十进制整数。

题目链接:https://leetcode.com/problems/complement-of-base-10-integer/

Difficulty: easy

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

分析

  • 考虑二进制的补码与原码的和的二进制表示为全是‘1’;
  • 那么每个数字的原码与补码的和只能是形如1、3、7、15等等,是2的n次幂减一;
  • 故可以得到N的补码的十进制表示。

参考代码

class Solution(object):
def bitwiseComplement(self, N):
    tar=1
    if(N==0):
        return 1
    while(tar-1<N):
        tar=tar*2
    return tar-N-1
-------------本文结束你这么美,还坚持读完了-------------