1
\$\begingroup\$

Here is my code:

noTest=int(input())
reverse=[]
nums=[]
for i in range(noTest):
 nums.append(int(input())) 
for num in nums:
 binary=bin(num)
 binNum=binary[2:]
 rev=binNum[::-1]
 rev=binary[:2]+rev+'0'*(32-len(rev))
 #print int(rev,2)
 reverse.append(int(rev,2))
for r in reverse:
 print(r)

Input:
The first line of input consists number of the test cases. Each test case
contains a single 32 bit integer.

Output:
Print the reverse of integer.

Input:00000000000000000000000000000001 =1
Output:10000000000000000000000000000000 =2147483648
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jan 4, 2018 at 9:20
\$\endgroup\$
2
  • \$\begingroup\$ I have... to what purpose? Know bit hacks? \$\endgroup\$ Commented Jan 4, 2018 at 10:00
  • \$\begingroup\$ What is the question here? \$\endgroup\$ Commented Apr 21, 2020 at 6:50

2 Answers 2

3
\$\begingroup\$

To expand on Caridorc's answer, you can merge bin and zfill when using str.format. Which gives a much cleaner read IMO:

int('{:032b}'.format(num)[::-1], 2)

Alternately you can use format, which would be:

int(format(num, '032b')[::-1], 2)
answered Jan 4, 2018 at 16:37
\$\endgroup\$
1
  • 1
    \$\begingroup\$ int(format(num, '032b')[::-1], 2) \$\endgroup\$ Commented Jan 4, 2018 at 17:29
3
\$\begingroup\$

You can avoid building a list of results to print them after, you can just print them as you calculate them.

Also you assign a lot of variables and:

binNum=binary[2:] 

is not explicit in removing the '0b' that Python prefixes, better is

.replace('0b','')

Also the padding with 0 logic that you write is already implemented in the zfill function, so you can avoid re-writing it yourself.

Finally, you should write a function to read the input to separate concerns and maybe reuse it in a similar problem.

Here are all my suggestions implemented.

def read_numbers(n):
 return [int(input()) for _ in range(n)]
for i in read_numbers( int(input()) ):
 binary_padded = bin(i).replace('0b','').zfill(32)
 print( int( binary_padded[::-1], 2) )
answered Jan 4, 2018 at 16:12
\$\endgroup\$
2
  • 3
    \$\begingroup\$ replace is worse since it does a search and traverses the whole string. \$\endgroup\$ Commented Jan 4, 2018 at 17:30
  • \$\begingroup\$ @Veedrac I think you are right, probably in this case [:2] should be used and maybe just adding a comment to explain the removal of '0b' \$\endgroup\$ Commented Jan 5, 2018 at 14:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.