题目地址: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; } };