4. leetcode 461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Input: x = 1, y = 4

Output: 2

Explanation:

1   (0 0 0 1)

4   (0 1 0 0)

↑   ↑

思路:就是求两数异或的二进制表示中有几个1.

如何求一个整数的二进制表示有几个一呢?

while(x){x=x&(x-1);count++;}

一个数减一之后,会把它最低位的一个1变成0,再与上它自己就会消掉最低位的1。

4. leetcode 461. Hamming Distance

上一篇:Leetcode#461. Hamming Distance(汉明距离)


下一篇:Poj OpenJudge 百练 1860 Currency Exchang