今天和大家聊的问题叫做 汉明距离,我们先来看题面:https://leetcode-cn.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, return the Hamming distance between them.
两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。给你两个整数 x 和 y,计算并返回它们之间的汉明距离。
示例
示例 1: 输入:x = 1, y = 4 输出:2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。 示例 2: 输入:x = 3, y = 1 输出:1
解题
依次记录两个数字每位是否相同,如果不同,计数器加一。
class Solution { public: int hammingDistance(int x, int y) { int count=0; while(x||y) { if(x%2!=y%2) ++count; x/=2; y/=2; } return count; } };
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。