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