前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 461 Hamming Distance

LeetCode 461 Hamming Distance

作者头像
Yano_nankai
发布2018-10-08 10:36:00
4000
发布2018-10-08 10:36:00
举报
文章被收录于专栏:二进制文集二进制文集

题目描述

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

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 2^31.

Example:

代码语言:javascript
复制
Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

分析

题目可以理解为:求两个数有多少位是不一样的。那么步骤可以为:

  1. 将两个数异或,结果记为 val
  2. 计算 val 有多少个 1

代码

代码语言:javascript
复制
public int hammingDistance(int x, int y) {
    int val = x ^ y;
    int result = 0;
    while (val != 0) {
        if ((val & 1) == 1) {
            result++;
        }
        val >>= 1;
    }
    return result;  
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.12.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档