LeetCode 1009. The inverse code of a decimal integer

LeetCode 1009. The inverse code of a decimal integer

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Problem :
    Every non-negative integer N has its binary representation. For example, 5 can be represented as binary "101", 11 can be represented as binary "1011", and so on. Note that, except for N = 0, there are no leading zeros in any binary representation. The binary one's complement means that each 1 is changed to 0 and each 0 is changed to 1. For example, the binary complement of the binary number "101" is "010". Given a decimal number N, return the decimal integer corresponding to the complement of its binary representation.
  • Example :
示例 1 :
输入:5
输出:2
解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
示例 2 :
输入:7
输出:0
解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
示例 3 :
输入:10
输出:5
解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
  • Tips :
    1. 0 <= N < 10^9
  • Code 1:
class Solution(object):
    def bitwiseComplement(self, N):
        """
        :type N: int
        :rtype: int
        """
        n = 0
        S = 0
        if N == 0:
            return 1
        while(2**n <= N):
            if 2 ** n <= N:
                S = S + 2 ** n
                n = n + 1
        return (N ^ S)
# 执行用时 :48 ms, 在所有Python3提交中击败了95.87%的用户
# 内存消耗 :13.1 MB, 在所有Python3提交中击败了83.01%的用户
  • Algorithm description:
    First judge N == 0the situation, and then judge how many Ndigits there are when converting to binary. When judging how many binary digits are, generate binary digits with all 1s corresponding to the digits 111……111. Then return Nto the SXOR result to the.
  • Code 2:
class Solution(object):
    def bitwiseComplement(self, N):
        """
        :type N: int
        :rtype: int
        """
        s = bin(N)[::-1]
        k = 0
        for i in range(len(str(s))-2):
            if s[i] == '0':
                k = k + (2**i)
        return k
# 执行用时 :68 ms, 在所有Python3提交中击败了33.49%的用户
# 内存消耗 :13 MB, 在所有Python3提交中击败了92.28%的用户
  • Algorithm description:
    first convert N into a binary string format, and then reverse; use the for loop to determine whether the character at the corresponding position is "1" or "0", if it is "0", the number will be "1" after inversion , Use k = k + (2**i)for accumulative calculation and output the result.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106626781