leetcode 1009. Complement of Base 10 Integer ( Python )

描述

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

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

For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.微信

Example 1:less

Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
複製代碼

Example 2:yii

Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
複製代碼

Example 3:svg

Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
複製代碼

Note:ui

0 <= N < 10^9
複製代碼

解析

根據題意,就是把 N 變成二進制的形態,而後進行 0-1 變換,將變換後的數字再轉換回十進制。時間複雜度爲 O(N),空間複雜度爲 O(N),N 是二進制的位數。es5

解答

class Solution(object):
def bitwiseComplement(self, N):
    """
    :type N: int
    :rtype: int
    """
    result = ""
    nbins = bin(N)[2:]
    for i in nbins:
        result += str(int(i)^1)
    return int(result, 2)            
複製代碼

運行結果

Runtime: 16 ms, faster than 77.81% of Python online submissions for Complement of Base 10 Integer.
Memory Usage: 11.7 MB, less than 79.49% of Python online submissions for Complement of Base 10 Integer.
複製代碼

每日格言:生命不等因而呼吸,生命是活動。spa

請做者喝吃泡芙
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索