Description
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 < 2^31.
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.
Solution 1(C++)
class Solution {
public:
int hammingDistance(int x, int y) {
int nx = x^y, cnt=0;
while(nx != 0){
if(nx%2==1) cnt++;
nx /= 2;
}
return cnt;
}
};
Solution 2(C++)
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }();
class Solution {
public:
int hammingDistance(int x, int y) {
int n = x ^ y;
int count = 0;
while(n){
count++;
n = n & (n-1);
}
return count;
}
};
算法分析
解法一自己写的,7ms耗时,解法二是我看提交结果中耗时最短的。经过前两道题: LeetCode-455. Assign Cookies、 LeetCode-155. Min Stack。发现这三者最快的解法第一句都是:
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }();
这就不得不想一想了,这一句不管什么情况,都能加,于是我也加了,结果,7ms耗时减少2~3ms。哇,这就很皮了。
根据网上的分析,其实这个就是加速程序读取数据的时间,从而达到缩短程序运行时间的目的。
程序分析
关于这个static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); 骚操作的解释网上也有很详尽的解释。其实原理简单来说,就是C++为了兼容C语言的输出格式,使用cin,cout等函数会降低输入输出速度,但是可以通过这些语句取消C++对C的兼容,从而提高效率。
用C++里面的cin读取数据,我们都知道它的速度相对于C里面的scanf是比较慢的
sync_with_stdio
这个函数是一个“是否兼容stdio”的开关,C++为了兼容C,保证程序在使用了std::printf和std::cout的时候不发生混乱,将输出流绑到了一起。可以在IO之前将stdio解除绑定,这样做了之后要注意不要同时混用cout和printf 之类。
tie
tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。
优秀的博客资料可以参考:ios::sync_with_stdio(false);(读入优化)、C++ 里利用 std::ios::sync_with_stdio(false) 解决TLE问题
、关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流、
总之,目前可以认为这是一中一定程度上可以缩短程序运行时间的万能钥匙。
本文介绍如何计算两个整数之间的汉明距离,并提供了两种C++实现方法。通过位运算技巧高效解决问题,同时探讨了提高程序效率的技巧。
376

被折叠的 条评论
为什么被折叠?



