def flippingBits(n):
binary_list=list(bin(n))[2::]
binary_32=''
binary_result=''
for item in binary_list:
if item=='1':
binary_32+='0'
else:
binary_32+='1'
if 32-len(binary_list)>0:
for i in range(32-len(binary_list)):
binary_result+='1'
binary_result+=binary_32
else:
binary_result=binary_32
result=int(binary_result, 2)
return result
This is a solution a made for a flipping bits in hacker rank:
The function receive an unsigned int, turn this number into a binary representation and flip all the bits in a 32 bits representation, then return the unsigned int number corresponding to the remaining binary number.
First I change into the binary representation using the bin() function, then i tansform that into a string with a for loop but changing every bit for the opposite(flipping), last I concatenate the string with the difference between the string length and the 32 spaces I need (32 bits), adding 1s to the rest of the string. Last I change into an integer using int(number, base) function.
I hope it helps you.
^operator.^ 0b111111110b10101 ^ 0b11111111 == 0b11101010a = 0b11111111^0b00101010 print(bin(a))This gives me The opposite