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 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步