LeetCode 476 Number Complement 補數

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.

題目解析

對於給定的數,輸出其補數,補數的定義爲將其對應的二進制位的數進行反轉,但是反轉的起始位從最高位的1開始的

解題思路

位操作符本身就有取反的符號,但是直接對num取反就是對所有位取反,而最高位1之前的0是不能反轉的,所有需要用mask標記最高位1之前所有0的位置,然後對mask取反後與對num取反後的結果

/* C++ */
class Solution {
public:
    int findComplement(int num) {
        unsigned mask;
        mask=~0;
        while(num & mask) mask<<=1;
        return ~mask & ~num;
        }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章