[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")
    }
}

    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/a1636edb8e65
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞