小练习:补数 (Number Complement)

1.eamples

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.
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.
Subscribe to see which companies asked this question.

 

2.solve

class Solution {
public:
    int findComplement(int num) {
        int mask=1;
        int temp = num;
        while(num)
         {
             num>>=1;
             mask<<=1;
         }
        mask--;
        return (temp^mask); 
    }
};

 

  

posted @ 2017-03-01 09:27  whlook  阅读(294)  评论(0编辑  收藏  举报