给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int i, high = 30, ans = m;
long num;
while(high>=0 && ((m>>high)&1)!=1)
high--;//找到最小的数的最高位
for(i = high; i >= 0; --i)
{
for(num = m; num <= n; ++num)
{ //2147483646、2147483647,int++溢出
if(((num>>i)&1)==0)
{
ans &= ~(1<<i);
break;
}
}
}
return ans;
}
};
324 ms 5.9 MB
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int move = 0;
while(m != n)
{
m >>= 1;
n >>= 1;
move++;
}
return m << move;
}
};
8 ms 6 MB
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有