小练习:补数 (Number Complement)

来源:互联网 发布:dnf游戏数据异常严重吗 编辑:程序博客网 时间:2024/06/07 09:27
1.eamples

Input: 5Output: 2Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Input: 1Output: 0Explanation: 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);     }};

 

  

原创粉丝点击