題目描述
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- 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,其按位取反的結(jié)果是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 的二進制數(shù)。
所以解決方法出來了:
- 找到最小的大于原數(shù)字的二進制值僅有一位為1的數(shù)脓钾;
- 將此數(shù)減1售睹;
- 與原數(shù)字按位求異或。
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")
}
}