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
思路:
and 的话必须两个都是1才是1.
先看最后一位。
101
110
111
抹掉,再看下一位
10
11
11
第一位,都是1,一共抹掉2个0,所以 1<<2
1
1
1
1 class Solution { 2 public: 3 int rangeBitwiseAnd(int m, int n) { 4 int cnt = 0; 5 while(m!=n){ 6 m>>=1; 7 n>>=1; 8 cnt++; 9 } 10 return n<<cnt; 11 12 } 13 };