[LeetCode]201.Bitwise AND of Numbers Range

简介:

题目

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

运行时间

这里写图片描述

目录
相关文章
LeetCode 307. Range Sum Query - Mutable
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
77 0
LeetCode 307. Range Sum Query - Mutable
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
79 0
LeetCode 304. Range Sum Query 2D - Immutable
|
索引
LeetCode 303. Range Sum Query - Immutable
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
69 0
LeetCode 303. Range Sum Query - Immutable
LeetCode 201. Bitwise AND of Numbers Range
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
54 0
LeetCode 201. Bitwise AND of Numbers Range

热门文章

最新文章