关闭

LeetCode Bitwise AND of Numbers Range

标签: leetcodejava
173人阅读 评论(0) 收藏 举报
分类:

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>


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:67207次
    • 积分:3299
    • 等级:
    • 排名:第10607名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论