476. 数字的补数

476. 数字的补数

给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。

示例 1:

  输入: 5
  输出: 2
解释: 5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2 。
示例 2:

  输入: 1
  输出: 0
解释: 1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。

 

#include<iostream>
using namespace std;
int main(){
  int x,n,count=-1,y=1;
  cin>>x;
  n=x;
  while(n>0){
      n>>=1;
      count++;
  }
  for (int i = 0; i < count; i++)
  {
      y|=(y<<1);
  }
  cout<<(x^y)<<endl;
}

 

class Solution {
public:
    int findComplement(int num) {
        int n=num,cnt=0;
        while(n){++cnt;n>>=1;}
        return num^((long)(1<<cnt)-1);
    }
};

 

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13547958.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/13547958.html