I’m new in python programming. just got stuck with this one problem. I have to take a natural number n as input and output will be a natural number m such that m>n and number of 1’s in m’s binary representation = number of 1’s in n’s binary representation.(sample input:23, output:27) here’s what i wrote. I’m having trouble with the while loop.
n=int(input('input number:'))
x=''
for i in range(1,n+1):
x=str(n%2)+x
n>>=1
List=[]
for i in x:
List.append(i)
n_count=List.count('1')
m=n+1
y=''
while m>n:
for i in range(1,m+1):
y=str(m%2)+y
m>>=1
List2=[]
for i in y:
List2.append(i)
m_count=List2.count('1')
if m_count==n_count:
print (m)
break
m=m+1
This sounds like homework, so I’ll just give you a hint. You can use the
binfunction to get the binary representation of an integer, rather than doing all that bit twiddling. To get a number with the same number of ones, just add a zero anywhere but in the first place, and check out what the second argument tointdoes to get back a number.