- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements
To Continue Learning Please Login
Login with Google