Maximum Number That Makes Result of Bitwise AND Zero Problem
#3125
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3125.
Given an integer n, return the maximum integer x such that x <= n, and the bitwise AND of all the numbers in the range [x, n] is 0.
Example 1:
Input: n = 7
Output: 3
Explanation:
The bitwise AND of [6, 7] is 6.
The bitwise AND of [5, 6, 7] is 4.
The bitwise AND of [4, 5, 6, 7] is 4.
The bitwise AND of [3, 4, 5, 6, 7] is 0.
Example 2:
Input: n = 9
Output: 7
Explanation:
The bitwise AND of [7, 8, 9] is 0.
Example 3:
Input: n = 17
Output: 15
Explanation:
The bitwise AND of [15, 16, 17] is 0.
Constraints:
1 <= n <= 10^15
Solution
Approach: Bit Manipulation
Find the highest set bit of n. The best x has that bit cleared and every lower bit set, that is, x = 2^k - 1 where 2^k is the highest power of two not above n. Then x & (x + 1) = 0, since x + 1 is that power of two.
Complexity: O(log n) time and O(1) space.
class Solution:
def maxNumber(self, n: int) -> int:
return (1 << (n.bit_length() - 1)) - 1