leetcode 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.



class Solution {
public:
	int rangeBitwiseAnd(int m, int n) {
		int re = 0;
		if (m ==n)
			return m;
		int k1 = log2(m);
		int k2 = log2(n);
		while (k2== k1)
		{
			re += pow(2, k1);
			m = m - pow(2, k1);
			n = n - pow(2, k1);
			k1 = log2(m);
			k2 = log2(n);
		}
		return re;
	}
};

accepted


你可能感兴趣的:(LeetCode)