Next Number Same Bitcount
Python
Hard
4 views
Problem Description
One non-negative integer n is provided (n>0). Compute the smallest integer > n that has the same number of set bits. Output it.
Input Format
One integer n.
Output Format
One integer next.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
n=int(s)
c=n
c0=0
c1=0
while (c & 1)==0 and c!=0:
c0+=1
c >>= 1
while (c & 1)==1:
c1+=1
c >>= 1
p=c0+c1
n |= (1<<p)
n &= ~((1<<p)-1)
n |= (1<<(c1-1)) - 1
sys.stdout.write(str(n))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!