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

2015-05-22 08:30:16

LeetCode 821 Card Flipping Game

2018-04-23 20:28:53

LeetCode 204:Count Primes

2015-05-08 18:40:26

LeetCode -- Bitwise AND of Numbers Range

2015-11-21 10:10:22

Bitwise AND of Numbers Range--LeetCode

2015-04-21 08:32:34

通过Leetcode::Bitwise AND of Numbers Range 深化对比特位计算的理解

2015-05-03 14:17:38

LeetCode[Bitwise]----Bitwise AND of Numbers Range

2016-05-02 23:40:48

[LeetCode] Bitwise AND of Numbers Range

2015-04-17 17:14:11

[Leetcode]Bitwise AND of Numbers Range

2015-09-01 13:18:37

Bitwise AND of Numbers Range——LeetCode

2015-06-29 23:50:02

不良信息举报

LeetCode Bitwise AND of Numbers Range