leetcode-476-Number Complement

题目描述:

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: 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.

要完成的函数:

int findComplement(int num)

说明:

1、这道题目要找出一个正整数(32位)所有不含前导零的位的相反数。比如5-101-010-2,2就是5的补数。

2、这道题目按照传统思路是,逐位处理原来的数,通过不断的“>>”,输出最后一位的数,然后这个数取反再乘以一个系数,最后求和,输出就是我们要的数。

如何判断当前已取到了所有不含前导零的数?只需要不断除以2,比如5/2=2,2/2=1,1/2=0,最后为0才停下,一共有三次除法,也就有三个不含前导零的数位。

这样子这道题也可以做,但是太慢了。我们再看看有没有更直接的办法。

3、我们发现5的补数是2,那么5+2=7=111(二进制),1的补数是0,1+0=1=1(二进制)。

我们已知有多少个不含前导零的数位,那么我们可以构造出7来,比如5有3个数位,那么7就是pow(2,3)-1;比如1有1个数位,那么1就是pow(2,1)-1

至此,我们找到了更好更直接的方法去处理。

代码如下:

    int findComplement(int num) 
    {
        int count=0,num1=num;
        while(num1!=0)
        {
            num1/=2;
            count++;
        }
        return pow(2,count)-1-num;
        
    }

上述代码实测6ms,beats 70.63% of cpp submissions。

猜你喜欢

转载自www.cnblogs.com/king-3/p/8965594.html