+ 1
Can anyone write the logic to find if any number is power of 2 or not in a single line?? Lets see who wins
A good logical question. Hint -it is done with an operator.
5 Réponses
+ 6
if(Math.sqrt(x) % 1 == 0)
+ 4
(Python)
print("1" not in bin(int(input()))[3:])
The powers of 2 in binary are 0b10, 0b100, 0b1000 etc., so if there is no "1" in the characters after "0b1", i.e. in the slice [3:] of the number converted to binary, it is a power of 2.
https://code.sololearn.com/cwaYyffRGYJI/?ref=app
+ 3
I found a one-line solution, which is very efficient.
The idea is that looking at the binary form of a power-of-2, it's always a 1 followed by zero of more 0's. For example, 8 is 1000.
Now, if we subtract 1 from such number, we get a sequence of 1's. For example: 8-1=7 which is 111.
Bit-wise xor of the two numbers is equal to their sum: 8 + 7 = 1000 + 111 = 1000 ^ 111 = 1111 = 15
To summarize, n is power of 2 iff the sum of n and n-1 is equal to the bit-wise xor of n and n-1
Here's the code:
https://code.sololearn.com/c2Vw3SZix9O6
0
https://code.sololearn.com/cLE0lGJ6DEkS/?ref=app