Skip to main content

Bitwise AND of Numbers Range

Medium
Data Structures and Algorithms
Editorial
Topics:
Bit Manipulation
Math
Iteration

Given two non-negative integers left and right, consider every integer in the inclusive range from left through right. The bitwise AND of two integers keeps a bit set only when that bit is set in both integers; applying it across a collection means every bit must be set in every value.

Return the single integer produced by bitwise-ANDing all integers in that range. The range may contain just one value, in which case return that value unchanged.

Example 1:

Input: left = 26, right = 30
Output: 24
Explanation: All values from 26 through 30 share only the bit pattern represented by 24, so the combined AND is 24.

Example 2:

Input: left = 7, right = 7
Output: 7
Explanation: The range contains one integer, so its bitwise AND is 7 itself.

Example 3:

Input: left = 8, right = 11
Output: 8
Explanation: The values 8, 9, 10, and 11 all retain the highest bit of 8, while lower bits are not set in every value.

Constraints:

  • 0 <= left
  • left <= right
  • right <= 2^31 - 1

Need help or want more practice?

Practise in an interviewGet AI Coach help