【LeetCode】Hamming Distance
问题网址 https://leetcode.com/problems/hamming-distance/
就是一个异或后,求1的位数的问题。
看到问题之后,首先困扰是: int能不能求异或?是不是要转成二进制才可以?
答案是肯定的。直接 x^y 就行了。
然后就是统计位数的问题了
答案一:https://discuss.leetcode.com/topic/72636/c-simple-solution-0ms
liupeng的答案
int hammingDistance(int x, int y) {
int tmpInt=x^y;
int dis=;
while(tmpInt)
{
if((tmpInt>>)<< != tmpInt)
//tmpInt右移一位,再左移动一位,相当于最后一位设为0;如果等于原数,就证明原来最后一位就是0.反之,是1
// 很巧妙
{
++dis;
}
tmpInt>>=;
}
return dis;
}
后话
如果真的要转成二进制,可以转成字符串
char str[10];
itoa(tmpInt, str, 2);
这个2 可以自由发挥了。别的进制也可以。
【LeetCode】Hamming Distance的更多相关文章
- 【leetcode】Edit Distance
Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert ...
- 【leetcode】1184. Distance Between Bus Stops
题目如下: A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between al ...
- 【leetcode】Edit Distance (hard)
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2 ...
- 【LeetCode】位运算 bit manipulation(共32题)
[78]Subsets 给了一个 distinct 的数组,返回它所有的子集. Example: Input: nums = [,,] Output: [ [], [], [], [,,], [,], ...
- 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
[LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...
- 【LeetCode】849. Maximize Distance to Closest Person 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】二叉查找树 binary search tree(共14题)
链接:https://leetcode.com/tag/binary-search-tree/ [220]Contains Duplicate III (2019年4月20日) (好题) Given ...
- 【LeetCode】哈希表 hash_table(共88题)
[1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target ...
- 【LeetCode】BFS(共43题)
[101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...
随机推荐
- java运行环境和运行机制
先来介绍三个概念: JVM----JAVA virtual machine java虚拟机:对字节码提供相同的接口,对操作系统提供不同的接口,以适应各个OS JRE----JAVA runt ...
- mysql 卸载 linux
root@localhost ~]# rpm -qa | grep -i mysqlMySQL-client-5.5.52-1.linux2.6.x86_64MySQL-server-5.5.52-1 ...
- linux运维自动化shell脚本小工具
linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...
- paper
1 IR 小目标检测 “Learning to detect small target A local kernel method” Xie K, Zhou T, Qiao Y, et al. Lea ...
- SVN在eclipse的整合应用
目前很多的Java.Flex.Android开发人员是用eclipse作为开发工具的,本文主要介绍SVN在eclipse平台中的整合应用. 我的eclipse版本是Version: 3.4.2.本身没 ...
- iOS当中一些常见的面试题
转自各方面..... 一.前言部分 文中的问题多收集整理自网络,不保证100%准确,还望斟酌采纳. 1.iOS9有哪些新特性? 答案: 1)改进了 Siri 基于日期.位置和相簿名称来搜索个人照片和视 ...
- Application Pool
- 省市联动sql脚本
create database ProCityData use Procitydata --创建Province(省表) create table Province ( ProID int prima ...
- js兼容性问题总结
JS中出现的兼容性问题的总结1.关于获取行外样式 currentStyle 和 getComputedStyle 出现的兼容性问题 我们都知道js通过style不可以获取行外样式,当我们需要获取行外 ...
- Xcode及obj-c的基础知识
1, 从简单的例程来看基本语法: 下面的代码是通过OSX-Application-Command Line Tool生成的: #import <Foundation/Foundation.h&g ...