201. Bitwise AND of Numbers Range (Bit)
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND(按位与) of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
思路:序列是按1递增的,所以必定先影响低位,按位与为1的情况必定发生在高位。两个数向右移,当两数相等,剩余的1便是按位与得到的1。
class Solution { public: int rangeBitwiseAnd(int m, int n) { int shift = 0; while(m!=n){ m >>= 1; n >>= 1; shift++; } return (m << shift); } };