LeetCode——十进制整数的反码

题目地址:https://leetcode-cn.com/problems/complement-of-base-10-integer/

解题思路:按位取反计算。注意不要想当然使用~,~10等于-11,而不是5。数据是以补码存储的,在计算机中,10的原码和补码为00...1010。取反后,补码变成11...0101,变成了负数,根据负数补码求原码可知,符号位不变,其余位数取反后加1,即原码:10...1010,加1后就是-11.

class Solution {
public:
    int bitwiseComplement(int N) {
        int ans=0,i=0;
        if(N==0)
            return 1;
        while(N){
            ans+=(1-(N&1))*(1<<(i++));
            N=(N>>1);
        }
        return ans;
    }
};

 

posted @ 2020-10-23 17:05  CCxiao5  阅读(159)  评论(0编辑  收藏  举报