# Program to find higher number with same number of set bits as n in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a number n; we have to find the smallest next higher number with the same number of 1s as n in binary form.

So, if the input is like n = 7, then the output will be 11, as 7 in binary is 0111 and next higher from 7 with three ones would be 11 which is 1011 in binary.

To solve this, we will follow these steps:

• copy := n, zeros := 0, ones := 0

• while copy is not 0 and copy is even, do

• zeros := zeros + 1

• copy = copy / 2

• while copy is odd, do

• ones := ones + 1

• copy = copy / 2

• right := ones + zeros

• n := n OR (2^right)

• n := n AND invert of ((2^right) - 1)

• n := n OR((2 ^ (ones - 1)) - 1

• return n

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, n):
copy = n
zeros = 0
ones = 0
while copy and not copy & 1:
zeros += 1
copy >>= 1
while copy & 1:
ones += 1
copy >>= 1
right = ones + zeros
n |= 1 << right
n &= ~((1 << right) - 1)
n |= (1 << ones - 1) - 1
return n

ob = Solution()
n = 7
print(ob.solve(n))

## Input

7

## Output

11
Published on 10-Nov-2020 07:40:38