Hamming Distance

xiaoxiao2021-02-27  161

开始刷LeetCode,逐步学习c++,从最简单的题目开始做: 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.

联系了关于c++中类的引用,我的代码如下:

#include<iostream> using namespace std; class Solution { public: int hammingDistance(int x, int y);//类内对函数声明 };//calss之后加分号 int Solution::hammingDistance(int x, int y)//作用域操作符::对类内函数定义,如果程序比较简单也可以直接在类的声明中进行定义 { int dist = 0, n = x ^ y;//n为x,y按位亦或结果,之后的步骤就是数n中有多少个1 while (n) { if (n % 2 == 1) { ++dist; } n = n >> 1;//向右移1位,相当于n/=2;还可以n&=(n-1),这种和n-1进行相与操作可以去掉n的最后一个1 } cout << dist << endl; return dist; }//不加分号 int main() { Solution n;//主函数调用类内函数,先要用定义好的类创建一个对象 n.hammingDistance(1,5); //调用类内public函数 return 0; }

学习总结: 1、对c++中类的定义、使用进行学习 2、c++中数字操作符进行学习

转载请注明原文地址: https://www.6miu.com/read-13273.html

最新回复(0)