前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-476-Number Complement

leetcode-476-Number Complement

作者头像
chenjx85
发布2018-05-22 16:27:38
4370
发布2018-05-22 16:27:38
举报

题目描述:

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

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

代码如下:

代码语言:javascript
复制
    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。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档