博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 461. Hamming Distance
阅读量:4097 次
发布时间:2019-05-25

本文共 928 字,大约阅读时间需要 3 分钟。

题目:

The  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 ≤ xy < 231.

Example:

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.
思路:

求两个数的汉明距离,用取余方法,算出x的二进制表示结果,若不到32位,则补0。并按位比较x与y

代码:

class Solution {public:	int hammingDistance(int x, int y) {		vector
x1, y1; int count = 0; int count_x = 0; int count_y = 0; while (x>0){//用取余方法,算出x的二进制表示结果 x1.push_back(x % 2); x = x / 2; count_x++; } while (count_x<31){//若不到32位,则补0 x1.push_back(0); count_x++; } while (y>0){//与x同样 y1.push_back(y % 2); y = y / 2; count_y++; } while (count_y < 31){ y1.push_back(0); count_y++; } for (int i = 0; i != 31; i++){ if (x1[i] ^ y1[i]){//按位比较x与y的 count++; } } return count; }};

转载地址:http://cnmii.baihongyu.com/

你可能感兴趣的文章
数据结构与算法7-栈
查看>>
线性数据结构学习笔记
查看>>
Java并发编程 | 一不小心就死锁了,怎么办?
查看>>
(python版)《剑指Offer》JZ01:二维数组中的查找
查看>>
(python版)《剑指Offer》JZ06:旋转数组的最小数字
查看>>
(python版)《剑指Offer》JZ13:调整数组顺序使奇数位于偶数前面
查看>>
(python版)《剑指Offer》JZ28:数组中出现次数超过一半的数字
查看>>
(python版)《剑指Offer》JZ30:连续子数组的最大和
查看>>
(python版)《剑指Offer》JZ32:把数组排成最小的数
查看>>
(python版)《剑指Offer》JZ02:替换空格
查看>>
JSP/Servlet——MVC设计模式
查看>>
使用JSTL
查看>>
Java 8新特性:Stream API
查看>>
管理用户状态——Cookie与Session
查看>>
最受欢迎的前端框架Bootstrap 入门
查看>>
JavaScript编程简介:DOM、AJAX与Chrome调试器
查看>>
通过Maven管理项目依赖
查看>>
通过Spring Boot三分钟创建Spring Web项目
查看>>
Spring的IoC(依赖注入)原理
查看>>
Guava快速入门
查看>>