Bitwise operations
Please help me solve the task, I can't make it shorter than 38 characters. Maybe someone understands code golf. Given a natural number x, it is less than 2 to the power of 31, return 1 if at least 1 odd bit of the number = 1, otherwise 0 if the numbering starts from the right with 0 and the rightmost bit 0 has a black position. Condition (code no longer than 23 characters)
6 Replies
What have you tried so far?
I've already decided f=x=>0xAAAAAAAA&x?1:0;
a bit shorter would be
f=x=>+(0xAAAAAAAA&x)
Thank you very much, I don't understand beaten things and code golf, I just ran into it
0xAAAAAAAA
is a hexadecimal number that translates to 10101010101010101010101010101010
in binary
the bitwise &
-operator compares each bit of x
with that 32 bit integer. if both bits are 1, it sets the resulting bit to 1 (otherwise 0)
if the result is non-zero (at least 1 bit position resulted in 1) than it is true (otherwise false)
the +(true/false)
will convert this boolean to 0
or 1
example
x = 5
x = 12
Thank you for the explanation, you won't believe it, but I dreamed of the decision 😅