LeetCode上的题目:
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
给定一个范围,将范围内的所有的数(包含首尾的数)进行按位与,返回结果。
冥思苦想写了一堆代码,结果单行代码就解决了,看来基础还是太太太薄弱了。
以下是自写代码,虽然思想是对的,但是随着输入数值变大,运算速度出奇的慢,直接超时。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int m=5,n=7;
int result=0,x=m;
int bit;
int s=0;
int lon=n-m;
while(x!=0)//计算最小数m的二进制位数
{
x=x/2;
s++;
}
for(int i=0;i<s;i++)//比m位数还多的位,和m相与肯定为0
{
int num=m;
bit =0;
for(int j=m;j<n+1;j++)
{
num=j;
num=num/pow(2.0,i);
bit=num%2;
if(bit==0) j=n+1;
}
if (bit==1)
{
result+=pow(2.0,i);
}
cout<<result<<endl;
}
system("pause");
return 0;
}
运行结果4
若m和n相差很大,则超时。
再看看人家的单行代码:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
return (m == n) ? m : (rangeBitwiseAnd(m >> 1, n >> 1) << 1);
}
};
虽然不太理解,但是实在佩服。