
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find higher number with same number of set bits as n in Python?n
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 Articles
- 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++
- Python program to count total set bits in all number from 1 to n.
- Find the largest number with n set and m unset bits in C++
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Maximum sum by adding numbers with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Find largest number smaller than N with same set of digits in C++
- Check if a number has same number of set and unset bits in C++
- Prime Number of Set Bits in Binary Representation in Python
- C# program to count total set bits in a number
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Program to find number of unique subsequences same as target in C++
- Find next greater number with same set of digits in C++
- Check if all bits of a number are set in Python

Advertisements