LeetCode -- 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.
就是對從m到n之間的數字做與運算。
思路:
本題的關鍵在於,求出了n& n-1為v,就可以直接把n設為v,而沒必要在求v與n-1之間的數了。
實現代碼:
public class Solution {
public int RangeBitwiseAnd(int m, int n)
{
while(n > m){
n = n & n-1;
}
return n & m ;
}
}