LeetCode Bitwise AND of Numbers Range

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.

Solution:

First, we should be clear that the answer should be no larger than both m and n.

Then we can just move the digit from ones to 32nd, loop continues until it reaches the condition that n equals m. And there might be the condition that n will never be equal to m, so just return 0. 

<span style="font-size:18px;">import java.util.*;

public class Solution {
	public int rangeBitwiseAnd(int m, int n) {
		int offset = 0;
		while (m > 0 && n > 0) {
			if (m == n)
				return n << offset;
			offset++;
			m >>= 1;
			n >>= 1;
		}
		return 0;
	}
}</span>


阅读更多
文章标签: leetcode java
个人分类: 算法/oj
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode Bitwise AND of Numbers Range

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭