码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode#201] Bitwise AND of Numbers Range

时间:2015-09-03 00:38:49      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

Problem:

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.

Analysis:

The idea behind this problem is not hard, you could easily think out the solution. But for the implementation, you may trap yourself into some sterotypes. 
Idea:
Since for bitwise ‘AND‘ operation, as long as there is a ‘0‘ appears, the digit should become 0.

Principle in digit change in range: (work for numerial system, binary system and other system too)
Start:  1011111100111010101010
End:    1011111110001010010101

To reach 10001010010101 from 00111010101010. We must start to add 
00000000000001 onto 00111010101010 => 00111010101011
...
We can we reach the ‘1‘ in high index, all digits behind after it must change once. That‘s to say, all the digits after 1 (include 1) should become 0.
answer: 1011111110000000000000

Algorithm:
Step 1: Find the first left bit ‘start‘ differ from ‘end‘.
Start:  10111111[0]0111010101010
End:    10111111[1]0001010010101

Step 2: Make all bits after the first different bits (include first different bit) into 0. The number is the answer we wish to get.
    10111111[0]0111010101010
=>  10111111000000000000

Great implementation:
Move bit to reach the answer!!!! See the solution!

Solution:

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        if (m < 0 || n < 0)
            throw new IllegalArgumentException("the passed in arguements is not tin the valid range!");
        int p = 0;
        while (m != n) {
            m = m >> 1;
            n = n >> 1;
            p++;
        }
        return m << p;
    }
}

 

[LeetCode#201] Bitwise AND of Numbers Range

标签:

原文地址:http://www.cnblogs.com/airwindow/p/4779668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!