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的二进制表示(不包括前缀0)中所有0变为1,1变为0

解答

解法1:(我)(11ms√)

例1:

5: 00000000000000000000000000000101
~5: 11111111111111111111111111111010 (补码形式,原码是10000000000000000000000000000110,值为-6)
-23: 11111111111111111111111111111000 (补码形式,原码是10000000000000000000000000001000,值为-23)
~5-(-23): 00000000000000000000000000000010 (值为2)

例2:

231-1: 01111111111111111111111111111111
~(231-1): 10000000000000000000000000000000 (值为-231)
-231: 10000000000000000000000000000000
~(231-1)-(-231): 00000000000000000000000000000000 (值为0)

注:此处(2<sup>31</sup>-1)-(-2<sup>31</sup>)不能写为(231-1)+231,因为int中正数231超出最大值范围,会被解析成231-1,而负数(-231)没有超出最小值范围


int的最大值:01111111111111111111111111111111 (值为231-1)
int的非最小值:11111111111111111111111111111111 (值为-(231-1) )
int的最小值:10000000000000000000000000000000 (值为-231)(特殊:使用以前的-0的补码来表示, 所以-231并没有原码和反码表示)

public class Solution {
    public int findComplement(int num) {
        return ~num - (int)-Math.pow(2,32-Integer.numberOfLeadingZeros(num));
    }
}


解法2:使用系统内置函数Integer.highestOneBit()(13ms)

Integer.highestOneBit() 返回一个int值:如果i具有'1'位,则返回值具有1个'1'位,其位置即是i的最高位(最左边)的'1'位的位置;如果i不具有'1'位,则i=0,返回0。例:Integer.highestOneBit(5) = 4,因为5的二进制表示为101,返回值的二进制表示为100

例1:

5: 00000000000000000000000000000101
~5: 11111111111111111111111111111010
a: 00000000000000000000000000001000 (a=Integer.highestOneBit(5) << 1)
~5+a: 00000000000000000000000000000010 (值为2)

例2:

231-1: 01111111111111111111111111111111
~(231-1): 10000000000000000000000000000000 (值为-231)
a: 10000000000000000000000000000000
~(231-1)+a: 00000000000000000000000000000000 (值为0)

public class Solution {
    public int hammingDistance(int x, int y){
        String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
        String str2 = str.replaceAll("1","");
        return str.length() - str2.length();
    }
}
posted @ 2017-02-18 09:36  妙音天女  阅读(223)  评论(0编辑  收藏  举报