Onee's Den
GithubTwitter
  • 简介
  • 项目
    • onee-framework
    • crypto-zombies
  • 博客
    • 以太坊区块数据详解
    • 区块链技术科普
    • Apollo 配置中心实战场景
      • 动态变更日志输出级别
    • JS 树形插件 jsTree 使用小记
    • MySQL 数据库的隔离级别
    • 优化 Lucene 搜索速度的一点建议
    • LeetCode 刷题之旅
      • 344. Reverse String
      • 412. Fizz Buzz
      • 461. Hamming Distance
      • 463. Island Perimeter
    • RabbitMQ 初次尝试
    • 记一次搭建 OpenVPN 过程
Powered by GitBook
On this page

Was this helpful?

  1. 博客
  2. LeetCode 刷题之旅

461. Hamming Distance

题目大意: 求两个数字的汉明距离,汉明距离是指两个数字对应位不同的数量,详情见示例

461. 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 < 2^31.

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.

解题思路:通过异或运算^将对应位不同的数值标示出来,使用 Integer.bitCount() 方法返回二进制1的数量

public int hammingDistance(int x, int y) {
    return Integer.bitCount(x ^ y);
}
Previous412. Fizz BuzzNext463. Island Perimeter

Last updated 3 years ago

Was this helpful?