461. Hamming Distance

The Hamming distancebetween two integers is the number of positions at which the corresponding bitsare different.
Given two integers xand y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
       ↑    ↑
The above arrowspoint to positions where the corresponding bits are different.

    谷歌翻译:两个整数之间的汉明距离是相应位不同的位置的数目。给定两个整数x和y,计算汉明距离。

    这个题目的意思是,输入两个整数,看这两个整数对应的二进制位有哪些不一样。

    Java的Unicode编码中,一个字符代表两个字节,32bit。可以用异或运算符,这个在以后的LeetCode当中运用的很多,所以多练习一下就会好了。异或是逻辑运算符。Java中逻辑与'&&'(),逻辑或'||',逻辑非'!',逻辑异或'^',逻辑与'&',逻辑或'|'。逻辑&&和&具有相同的功能,两边同时为true,则结果为true。但是对于&&,已知左边为false,则不计算后面的表达式,因为结果已经确定了为false;逻辑||和'|',两边同时为false,则结果为false。否则有一个为true,则结果为true。但是对于||,当左边有一个为true,则不计算后面的表达式。异或记住"同0异1",相同位是0,不同则为1。代码如下:

public class Solution{

    public int hammingDistance(int x, int y) {

        int temp=x^y;//^在word中复制过来,两个整数异或,然后数一的个数

          int dis=0;

              while (temp != 0) {

                     if ((temp >> 1)<< 1 != temp) { // temp右移一左移动一位,相当于最后一位设为0;如果等于原数,就证明原来最后一位就是0.这个比较巧妙,也可以将这个数变为二进制,然后存储在集合中,遍历其中1的个数

                            ++dis;

                     }

                     temp >>= 1;

              }

              return dis;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值