题意:
给定一段区间,返回区间内所有数按位与的结果。
分析:
本来的思路是处理31位,用数组,对于每一位,全1是1,有0则0,这样需要双重循环,超时
public class Solution { public int rangeBitwiseAnd(int m, int n) { int num = 0; int t = 1; for(int i=0; i<31; i++){ for(int j=m; j<=n; j++){ if((j>>i) != ((j>>i)|1)){ //最低位即研究位是0 break; } if(j==n){ num += t; } } t = t*2; } return num; } } 还是得找规律,规律不是自己找的:找最高位的同1. public class Solution { public int rangeBitwiseAnd(int m, int n) { if(m == 0){ return 0; } int moveFactor = 1; while(m != n){ m >>= 1; n >>= 1; moveFactor <<= 1; } return m * moveFactor; } }