leetcode-461-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 = 4Output: 2Explanation: 1 (0 0 0 1) 4 (0 1 0 0)↑ ↑The above arrows point to positions where the corresponding bits are different.
要完成的函数:
int hammingDistance(int x, int y)
说明:
给定两个32位的有符号型整数,当每一位不相同时,加上1,输出最后一共有多少位不相同。
代码如下:
int hammingDistance(int x, int y) {int xx,yy,count=0;for(int i=0;i<32;i++){xx=x&1;yy=y&1;if(xx!=yy)count++;x>>=1;y>>=1;}return count;}
代码浅显易懂,实测6ms,beats 72.58% of cpp submissions。
这道题在评论区还看到了令人耳目一新的做法,采用异或,当两位相同时输出0,当两位不同时输出1。不过这种做法的时间花费实际还是跟上述代码差不多的。
代码如下:
int hammingDistance(int x, int y) {int result=x^y,t1,count=0;for(int i=0;i<32;i++){t1=result&1;if(t1==1)count++;result>>=1;}return count;}
转载于:https://www.cnblogs.com/chenjx85/p/8948404.html
leetcode-461-Hamming Distance相关推荐
- Leetcode 461. Hamming Distance JAVA语言
The Hamming distance between two integers is the number of positions at which the corresponding bits ...
- [LeetCode] 461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits ...
- LeetCode 461 Hamming Distance(汉明距离)
Q:The Hamming distance between two integers is the number of positions at which the corresponding bi ...
- LeetCode 461. Hamming Distance
题目: The Hamming distance between two integers is the number of positions at which the corresponding ...
- 【LeetCode】461. Hamming Distance (java实现)
2019独角兽企业重金招聘Python工程师标准>>> 原题链接 https://leetcode.com/problems/hamming-distance/ 原题 The Ham ...
- LeetCode之Hamming Distance
1.题目 The Hamming distance between two integers is the number of positions at which the corresponding ...
- 461. Hamming Distance【数学|位运算】
2017/3/14 15:23:55 The Hamming distance between two integers is the number of positions at which the ...
- LeetCode之461. Hamming Distance
------------------------------------------------------------------ AC代码: public class Solution {publ ...
- LeetCode(191 461):位1的个数 Number of 1 Bits 汉明距离 Hamming Distance(Java)
2019.9.14 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) github:https://github.com/ChopinXBP/LeetCode-Babel 之前在 ...
- C#LeetCode刷题之#461-汉明距离(Hamming Distance)
问题 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目. 给出两个整数 x 和 y,计算它们之间的汉明距离. 注意:0 ≤ x, y < 231. 输入: x = 1, y = ...
最新文章
- linux 6.7 nfs安装yum,centos7下NFS使用与配置
- linux 从行查看文件,linux 查看文件内容
- Python 代码性能优化技巧
- modelsim的库仿真流程--1
- 提示语_《流浪地球》里洗脑的交通提示语怎么来的?吴京可能要“负全责”
- windbg学习.formats--转换成各种进制
- 组合数学 —— 容斥定理
- python unicode 编程 pdf,Python | Python学习之unicode和utf8
- 虚拟DOM和DIFF算法的理解
- Python字符串学习
- er图-为什么画er图?有哪些规范?
- 大气数据计算机英语,大气数据计算机(ADC)
- 小程序scroll-view,滚动到最低_小程序滚动到底部
- C#从字节数组截取片段(转载)
- android系统关机广播,Android开机广播和关机广播
- 中兴服务器告警,中兴ZXPCS 10.0网管系统简介
- P4913 【深基16.例3】二叉树深度
- sla的三个服务等级_你知道吗?阿里云最新发布的服务等级协议SLA已领先全球水平...
- json 转 csv python
- 计算机网络翻译,COMPUTERNETWORK_计算机网络(英语论文翻译)