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。

 

posted @ 2017-04-09 21:19  蓦然闻声  阅读(85)  评论(0编辑  收藏  举报