[LeetCode By Go 4]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.

解题思路

这题最容易想到的方法就是直接用~按位取反了,但这样有个明显的问题就是即使是前缀的0也会被取反,如int型5的二进制表示是0000 0000 0000 0000 0000 0000 0000 0101,其按位取反的结果是1111 1111 1111 1111 1111 1111 1111 1010,这样前面就多了29个1,我们还得想办法把这些1变成0,从而得到0000 0000 0000 0000 0000 0000 0000 0010,即十进制2。

但我们不妨换个思路,用异或^来求解,比如101 ^ 111 = 010。那么怎么得到111呢?考虑111 + 1 = 1000,而1000又是 最小的 大于101的 只有一位是1 的二进制数。

所以解决方法出来了:

  1. 找到最小的大于原数字的二进制值仅有一位为1的数;
  2. 将此数减1;
  3. 与原数字按位求异或。

Code

Number_Complement.go

package _476_Number_Complement

func FindComplement(num int) int {
    tmpnum := num
    var ret int
    for tmpnum > 0 {
        ret = ret * 2 + 1
        tmpnum = tmpnum >> 1
    }

    ret = ret ^ num

    return ret
}

Test

Number_Complement_test.go

package _476_Number_Complement


import "testing"


func TestFindComplement(t *testing.T) {
    ret := FindComplement(5)

    if 2 == ret {
        t.Logf("pass")
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 昨天一大早,微信聊天群显示有336条未读消息,我还纳闷怎回事就点开看看,原来是十一年前的高三11班,微信真是好,一...
    我是一朵老云阅读 2,929评论 0 1
  • 战争是在霍格沃茨特快上开始的。 不知为何,哈利的脑海中一直回荡着这句话。不,他想,准确地说,是从德...
    枪旗摘春明阅读 31,392评论 2 10
  • 稀里糊涂来到武汉,不知不觉已经有10个年头了,感受到大武汉每天都在认真的不一样,想想10年前闯武汉,手里拿...
    周巍阅读 1,526评论 0 2

友情链接更多精彩内容