Master Solution in python 3:
for i in input().split():
print(2**(len(bin(int(i)))-2)-1)
for i in input().split():
print(2**(len(bin(int(i)))-2)-1)
As you can see, just 2 lines of code in python 3 ( though a bit tricky ) and the problem is solved. :)
This problem was the simplest of all and even more simple for pythonheads.
The purpose of this problem was to make the contestants acquainted with bitwise operations. But as you can see, it was not at all necessary to perform bitwise OR on all integers upto n. Because the result is always 2^[log_2(n)+1] -1, where [] is the greatest integer function and log_2 means logarithm of base 2.
But here is an optimisation trick. You wont need to calculate the log at all, because the value of [log_2(n)+1] is equal to the number of digits when n is written in binary. And all numbers are stored in binary in the computers memory. So, the trick was to find out the length of the number when written in binary.
Many might ask why I wrote " 2**(len(bin(int(i)))-2)-1 ". In python 3 when you represent a number in binary using the bin function, the output is a string starting with '0b'. For example bin(6) is 0b110. Hence the length of the number is equal to the ( length of the output string - 2 ).
No comments:
Post a Comment