[LeetCode]201.Bitwise AND of Numbers Range

160 篇文章 28 订阅

题目

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.

思路

[5, 7]里共有三个数字(5,6,7),二进制分别为:

1 01  1 10  1 11

相与后的结果为100

[9, 11]里共有三个数字(9,10,11),二进制分别为:

1 001  1 010  1 011

相与后的结果为1000

[26, 30]里共有五个数字(26,27,28,29,30),二进制分别为:

11 010  11 011  11 100  11 101  11 110

相与后的结果为11000

仔细观察我们可以得出,我们要求出的结果就是给定范围内所有数的左边公共1的部分,其他位都为0。

代码

/*---------------------------------------
*   日期:2015-04-26
*   作者:SJF0115
*   题目: 201.Bitwise AND of Numbers Range
*   网址:https://leetcode.com/problems/bitwise-and-of-numbers-range/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        if(m == 0){
            return 0;
        }//if
        int count = 0;
        while(m != n){
            // 左移一位
            m >>= 1;
            n >>= 1;
            ++count;
        }//while
        return m << count;
    }
};

int main(){
    Solution solution;
    int m = 9;
    int n = 11;
    int result = solution.rangeBitwiseAnd(m,n);
    // 输出
    cout<<result<<endl;
    return 0;
}

运行时间

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值