LeetCode 461. Hamming Distance

原题链接在这里:https://leetcode.com/problems/hamming-distance/

题目:

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 ≤ xy < 231.

Example:

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.

题解:

Bits different自然而然就想到了xor.

利用Number of 1 Bits的数xor 结果的bit 1个数.

或者用Integer.bitCount() function.

Time Complexity: O(1). Space: O(1).

AC Java:

1 public class Solution {
2     public int hammingDistance(int x, int y) {
3         return Integer.bitCount(x^y);
4     }
5 }

 跟上Total Hamming Distance.

posted @   Dylan_Java_NYC  阅读(295)  评论(0)    收藏  举报
编辑推荐:
· 记一次 ADL 导致的 C++ 代码编译错误
· MySQL查询执行顺序:一张图看懂SQL是如何工作的
· 为什么PostgreSQL不自动缓存执行计划?
· 于是转身独立开发者
· C#.Net筑基-泛型T & 协变逆变
阅读排行:
· C#/.NET/.NET Core优秀项目和框架2025年6月简报
· Cursor 1.2重磅更新,这个痛点终于被解决了!
· C#开发的Panel滚动分页控件(滑动版) - 开源研究系列文章
· 上周热点回顾(6.30-7.6)
· .NET AI 模板
点击右上角即可分享
微信分享提示