LeetCode Bitwise AND of Numbers Range

原创 2015年09月06日 08:33:05

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 201 Bitwise AND of Numbers Range

Given a range [m, n] where 0

Leetcode 201 Bitwise AND of Numbers Range 区间内整数按位与

给出一个区间 [m, n],其中0

leetcode 201:Bitwise AND of Numbers Range

Question:   Given a range [m, n] where 0
  • sj_lxd
  • sj_lxd
  • 2015年09月01日 19:33
  • 207

LeetCode 201 Bitwise AND of Numbers Range

Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4. 思路:介于(包括...

Leetcode 201 - Bitwise AND of Numbers Range(bit & math)

题意给定两个数m和n,并且m≤nm \leq n,求f(m, n) = m & (m + 1) & (m + 2) & ... & n的值。思路算法1我们知道,在范围[m,n][m, n]内,对于二进...
  • Lzedo
  • Lzedo
  • 2017年03月10日 17:45
  • 105

[Leetcode] 201. Bitwise AND of Numbers Range 解题报告

题目: Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4. ...

Leetcode-201- Bitwise AND of Numbers Range

Given a range [m, n] where 0 For example, given the range [5, 7], you should return 4.  题意:m到n若干个数字...

leetCode191/201/202/136 -Number of 1 Bits/Bitwise AND of Numbers Range/Happy Number/Single Number

链接:https://leetcode.com/problems/number-of-1-bits/ 此题关键是如何判断一个数字的第i为是否为0  即: x& (1 class Solution { ...

201 Bitwise AND of Numbers Range

题目介绍:将m到n之间的所有的数相与,得到其结果 要点:最笨的方法是将所有的数真正的相与,这无疑耗时效率低下。通过分析可以发现,若两个数最高有效位长度不相等,则最终结果一定是 仅含n的最高有效位的值,...

LeetCodeOJ_201_Bitwise AND of Numbers Range

Given a range [m, n]where 0
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Bitwise AND of Numbers Range
举报原因:
原因补充:

(最多只允许输入30个字)