- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Questions & Answers
- Next higher number with same number of set bits in C++
- Maximum number of contiguous array elements with same number of set bits in C++
- Find largest number smaller than N with same set of digits in C++
- Find the largest number with n set and m unset bits in C++
- Python program to count total set bits in all number from 1 to n.
- Number of integers with odd number of set bits in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Check if a number has same number of set and unset bits in C++
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Program to find number of unique subsequences same as target in C++
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Find next greater number with same set of digits in C++
- Prime Number of Set Bits in Binary Representation in Python
- C# program to count total set bits in a number
- Number of 1 Bits in Python

Advertisements