476. Number Complement(C语言)

来源:互联网 发布:.shop域名上线时间 编辑:程序博客网 时间:2024/05/17 21:40

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

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.

Example 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.
提意:

给一个[-1000,1000]区间内的数,对它二进制的数求反然后输出

思路:

输入:num

求反:因为是二进制的操作,所以就想到什么位运算(^)、与运算(&)、左移(<<)右移(>>)这些东西

   举例子101取反就是010110取反就是001,100取反就是011

  位运算的规则是相同的取0,不同的取1

          那么101111进行位运算得出的就是010,110111的结果是001,100111位运算的结果就是011

          下一步就是想怎么找到和num位数相同的111

  看了眼答案,discuss给出的结果就是for(i=1;i<=num;i*=2)     num^=i;

  也就是说,在i=1,2,4,8,16,32....的时候 循环和num进行位运算,也就是i=1,10,100,1000,1000

          很好,正好可以和num的位数相同,只不过是一位一位的进行位运算

输出:num

int findComplement(int num) {    //int num=0;    long i=1;    for(i=1;i<=num;i*=2){        num^=i;    }    return num;}
tips:

1.因为num有正有负,所以i变成long型

2.for(i=1;i<=num;i*=2) 里面的i*=2不能写成i*2....我也不知道为什么


0 0