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.
For example, given the range [5, 7], you should return 4.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class  {
public:
int rangeBitwiseAnd(int m, int n) {
if(m==n)return m;
int temp=1<<31;
int result=0;
for(int i=0;i<31;i++){
if((m&temp)==(n&temp))result|=m&temp;
temp>>=1;
}
return result;
}

};