【LeetCode】461.Hamming Distance_EASY(一)

来源:互联网 发布:5s是否支持4g网络 编辑:程序博客网 时间:2024/05/01 19:18

大三实在有空,闲来无事便想刷一刷LeetCode上的题,记录在博客上也算是想激励自己坚持下去吧,这是按照难度排序的第一道题。
因为以后想从事java相关的岗位,所以都会用java来解决问题。

461.Hamming Distance

Description:
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:   0x,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.

以上是题目,其实就是求两个整数的汉明距离,对于java来说,如果你知道bitCount方法的话,其实就是一行代码的事儿:
PS:  bitCount方法——获取二进制补码中1位的数量

Solution:

public class Solution {    public int hammingDistance(int x, int y) {        return Integer.bitCount(x^y);       }}

第一题结束,还是挺简单的,呼。

0 0