476. Number Complement(python+cpp)
題目:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
解釋: 二進位制取反。 python投機取巧: 先用bin變成二進位制,然後用1減去每一位進行翻轉 c++: 如果我們能知道該數最高位的1所在的位置,就可以構造一個長度和該資料所佔位置一樣長的一個掩碼mask,然後該數字和mask進行異或即可。 例如:5的二進位制是101,我們的構造的掩碼為mask=111,兩者異或則為010,即是所要的結果。 取反就是和與它長度相同的全1二進位制進行異或
python程式碼:
class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ num_bin=bin(num)[2:] result='' for n in num_bin: r=str(1-int(n)) result+=r return int(result,2)
c++程式碼:
class Solution {
public:
int findComplement(int num) {
int mask=1;
int n=num;
while(n>0)
{
mask=mask<<1;
n=n>>1;
}
return (mask-1)^num;
}
};
python寫法:
class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ n=num mask=1 while(n>0): mask=mask<<1 n=n>>1 return (mask-1)^num
這種異或的寫法速度顯然更快。
總結: 取反就是和與它長度相同的全1二進位制進行異或