题目链接:https://leetcode.com/problems/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
思路:
暴力肯定会超时的,于是找一下规律。
由于与&的关系,遇0就是0。
首先考虑,
如果区间是[k,k]那么返回值就是k。
如果区间是[m,n],即此时n > m,那么从m变化到n这些数字,
bit的最低位最后的“与”的结果一定是0,因为从m变化到m+1,
如果m的最低位是0,那么此时变化到1,与之后这一位肯定还是0,
如果m最低位是1,那么m+1最后一位肯定是0.所以与的最终结果最低位肯定还是0.
所以直接比较m和n是否相等,如果不相等,就m>>1,n>>1,同时统计0的位数,最后再左移回来。
AC:
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int count=0;
while(m!=n){
m=m>>1;
n=n>>1;
count++;
}
return (m<<count);
}
}