Loading

【leetcode】476. Number Complement

  The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.

  • For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

Given an integer num, return its complement.

Example 1:

Input: num = 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.


          这题考察对于数字基本的位存储的信息,依次取出数字的最低位,如果是0则翻转相加,index记录当前的阶数,num补零右移,直到为0位置。

class Solution {
public:
    int findComplement(int num) {
        int index=0;
        int tmp=0;
        while(num){
            if((num&1)==0){
                tmp=tmp+pow(2,index);
            }
            num=num>>1;
            index++;
        }
        return tmp;
    }
};

      还有一种更加trick的处理方式。利用bit mask的方式计算

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

 

posted @ 2021-12-27 16:41  aalanwyr  阅读(39)  评论(0编辑  收藏  举报