Amateur hour!
So, I never really seen binary, hex, or any of that stuff until the other day, and the question calls for converting integer to binary and binary to integer. This code feels wrong on so many levels:
Code:
def intToBinary(x):
ans = ''
while x > 0:
ans += str(x % 2)
x //= 2
return int(ans[::-1])
def binaryToInt(x):
sx = str(x)[::-1]
power = 0
ans = 0
for i in sx:
ans += int(i) * 2**power
power += 1
return ans
To confirm this somewhat works (yes, it fails for zero):
Code:
print(intToBinary(9))
print(intToBinary(1))
print(intToBinary(10))
print(intToBinary(100))
print(intToBinary(15))
print(intToBinary(89))
print(binaryToInt(intToBinary(9)))
print(binaryToInt(intToBinary(1)))
print(binaryToInt(intToBinary(10)))
print(binaryToInt(intToBinary(100)))
print(binaryToInt(intToBinary(15)))
print(binaryToInt(intToBinary(89)))
>>> 1001
1
1010
1100100
1111
1011001
9
1
10
100
15
89
Is that really the best that can be done without actually pushing bits?