GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing leetcode-in-java.github.io — LeetCode-in-Java

LeetCode-in-Java

201. Bitwise AND of Numbers Range

Medium

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Example 1:

Input: left = 5, right = 7

Output: 4

Example 2:

Input: left = 0, right = 0

Output: 0

Example 3:

Input: left = 1, right = 2147483647

Output: 0

Constraints:

  • 0 <= left <= right <= 231 - 1

Solution

public class Solution {
    private static final int[] MASKS =
            new int[] {
                0,
                0x80000000,
                0xC0000000,
                0xE0000000,
                0xF0000000,
                0xF8000000,
                0xFC000000,
                0xFE000000,
                0xFF000000,
                0xFF800000,
                0xFFC00000,
                0xFFE00000,
                0xFFF00000,
                0xFFF80000,
                0xFFFC0000,
                0xFFFE0000,
                0xFFFF0000,
                0xFFFF8000,
                0xFFFFC000,
                0xFFFFE000,
                0xFFFFF000,
                0xFFFFF800,
                0xFFFFFC00,
                0xFFFFFE00,
                0xFFFFFF00,
                0xFFFFFF80,
                0xFFFFFFC0,
                0xFFFFFFE0,
                0xFFFFFFF0,
                0xFFFFFFF8,
                0xFFFFFFFC,
                0xFFFFFFFE
            };

    public int rangeBitwiseAnd(int left, int right) {
        return left == right ? left : right & MASKS[Integer.numberOfLeadingZeros(left ^ right)];
    }
}
This site is open source. Improve this page.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.