Leetcode刷题(3)

来源:互联网 发布:nginx停止命令 编辑:程序博客网 时间:2024/06/05 08:16

Given a positive integer,output its complement number. The complement strategy is to flip the bits ofits 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: 5
Output: 2
Explanation: 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: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Subscribe tosee which companies asked this question.


我的解答:

classSolution {

public:

    int findComplement(int num) {

        int a[32];

        int b[32];

        int find = 0;

        int i = 0;

        while(num != 0) {

            a[i] = num % 2;

            b[i] = 1 - a[i];

            num = num - a[i];

            num = num / 2;

            i++;

        }

            for(int j=0; j<i; j++) {

                find = find + b[j]*pow(2,j);

            }

            return find;

    }

};

 

比较经典的答法:

classSolution {

public:

    int findComplement(int num) {

        unsigned mask = ~0;

        while (num & mask) mask <<=1;  //还未理解这块

//比如101

                                                                        //那mask应该是11111100,为什么是11111000?

        return ~mask & ~num;

    }

};

For example,

num          = 00000101mask         = 11111000~mask & ~num = 00000010

0 0