I am doing a hackerrank example called Flipping bits where given a list of 32 bit unsigned integers. Flip all the bits (1->0 and 0->1) and return the result as an unsigned integer. The correct code is:
def flippingBits(n):
seq = format(n, '032b')
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
I dont understand the last line, what does the ''. part do? and why is there a ,2 at the end?
I have understood most of the code but need help in understanding the last part.
CodePudding user response:
what does the ''. part do
''
represents an empty string which will be used as separator to join collection elements into string (some examples can be found here)
and why is there a ,2 at the end?
from int
docs:
class int(x=0)
class int(x, base=10)
Return an integer object constructed from a number or string x
In this case it will parse the string provided in binary format (i.e. with base 2) into int.
CodePudding user response:
I hope the below explanation helps:
def flippingBits(n):
seq = format(n, '032b') # change the format from base 10 to base 2 with 32bit size unsigned integer into string
return int(''.join(['0' if bit == '1' else '1' for bit in seq]), 2)
# ['0' if bit == '1' else '1' for bit in seq] => means: build a list of characters from "seq" string
# in which whenever there is 1 convert it to 0, and to 1 otherwise; then
# ''.join(char_list) => means: build string by joining characters in char_list
# without space between them ('' means empty delimiter); then
# int(num_string, 2) => convert num_string from string to integer in a base 2
Notice that you can do the bit flipping by using bit-wise operations without converting to string back and forth.
def flippingBits(n):
inverted_n = ~n # flip all bits from 0 to 1, and 1 to 0
return inverted_n 2**32 # because the number is a signed integer, the most significant bit should be flipped as well