LeetCode 461. Hamming Distance

来源:互联网 发布:数据质量责任追究制度 编辑:程序博客网 时间:2024/06/16 06:27

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.

Code 1

class Solution {public:    int hammingDistance(int x, int y) {        int sum = 0;        for (int i = 0; i < 31; i++)          sum += (x & (1 << i)) != (y & (1 << i));        return sum;    }};

Code 2

class Solution {public:    int hammingDistance(int x, int y) {        int z=x^y, sum=0;        while (z) {            sum += z & 1;            z = z >> 1;        }        return sum;    }};

Appendix

  • Link:https://leetcode.com/problems/hamming-distance/
  • Run Time:
    – Code 1: 3ms
    – Code 2: 3ms
0 0
原创粉丝点击