其他分享
首页 > 其他分享> > [LeetCode 201.] Bitwise AND of Numbers Range

[LeetCode 201.] Bitwise AND of Numbers Range

作者:互联网

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.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

解题思路

题目的意思很简单,就是给定两个端点m和n,求问闭区间内部所有数字的二进制与的值。

参考代码

/*
 * @lc app=leetcode id=201 lang=cpp
 *
 * [201] Bitwise AND of Numbers Range
 */

// @lc code=start
class Solution {
public:
/*
    int rangeBitwiseAnd(int m, int n) {
        int res = 0xFFFFFFFF;
        int bkp = 0xFFFFFFFF; if(n==2147483647){bkp=n;n--;}
        for (int i=m; i<=n; i++) {
            res &= i;
            if (res == 0) break; // fast fail
        }
        res &= bkp; // avoid i++ overflow
        return res;
    } // AC, brute force beats 5.43 % of cpp submissions
*/
/*
    // bitwise longest common prefix
    int rangeBitwiseAnd(int m, int n) {
        int offset = 0;
        while (m != n) {
            m >>= 1;
            n >>= 1;
            offset++;
        }
        return n << offset;
    } // AC, beats 44.2 % of cpp submission
*/
    // bitwise longest common prefix
    int rangeBitwiseAnd(int m, int n) {
        //  0 <= m <= n <= 2147483647
        while (m < n) {
            n &= (n - 1);
        }
        return n;
    } // AC
};
// @lc code=end

标签:201,int,res,Bitwise,二进制,Range,LeetCode
来源: https://www.cnblogs.com/zhcpku/p/14317902.html