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 ≤ x
, y
< 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 }
【推荐】FlashTable:表单开发界的极速跑车,让你的开发效率一路狂飙
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次 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 模板