Description:
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.
Code:
1 int rangeBitwiseAnd(int m, int n) { 2 /* 3 分析:经过举例发现,只要m与n之间出现2的k次方和2的k次方-1,则结果必然为0;否则,说明m一定大于等于最接近n的2的k次方。 4 */ 5 6 //使用数学函数时注意要进行强制类型转换,否则可能出现计算结果错误的问题 7 unsigned int x = pow((float)2,(int)(log((double)n)/log((double)2))); 8 if ( m+1 <= x ) 9 return 0; 10 else 11 { 12 //x要为无符号整型,才能得到1111111111 13 x = ~0; 14 for (int i = m; i <=n && i>=0; i++) 15 x = x&i; 16 return x; 17 } 18 }