1537. Same Bits Next Up

Medium3.5 points estimatedBit ManipulationBitmask

A feature-flag service stores a set of enabled flags as the bits of a positive integer n. When the set must be bumped to the next configuration, the service wants the smallest integer strictly greater than n that has exactly the same number of set bits as n.

Return that integer, or -1 if it does not fit into a signed 32-bit integer (that is, if it would exceed 2^31 - 1). For example, 6 (binary 110) is followed by 9 (binary 1001), and 7 (binary 111) by 11 (binary 1011).

Input: one integer n. Output: one integer. Use the lowest-set-bit trick: with c = n & -n and r = n + c, the answer is (((r ^ n) >> 2) / c) | r. Do the arithmetic in 64 bits because r can pass 2^31. Time O(1), space O(1).

Example 1

Input:
n = 6
Output:
9
Explanation:

Numbers 7 and 8 have three and one set bits; 9 = 1001 is the first above 6 with two set bits.

Example 2

Input:
n = 2147483647
Output:
-1
Explanation:

All 31 low bits are set, and the next number with 31 set bits needs 32 bits, so the result is -1.

Constraints

1 ≤ n ≤ 231 - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…