C++给定范围进行按位与运算

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);
    }
};

虽然不太理解,但是实在佩服。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值