LeetCode Bitwise AND of Numbers Range

来源:互联网 发布:135端口入侵 编辑:程序博客网 时间:2024/05/20 03:36

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
原创粉丝点击