Convert a given integer to binary. Return 1 when ANY odd bit of x equals 1; 0 otherwise.
Examples
any_odd(2) will return 1 because at least one odd bit is 1 (0010).
any_odd(170) will return 1 because all of the odd bits are 1 (10101010).
Tests
any_odd(5)
any_odd(7)
any_odd(10)
Good luck!
This challenge comes from mtruong1999 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (9)
Here is a C++ solution, (considering given number is positive and 32-bit integer)
This C++ solution supports a number of any size (byte, 16-bit, 32-bit, etc), and compiles down to just a single CPU instruction for every invocation of
any_odd
.Note that without the
reinterpret_cast
, an unnecessarycdqe
instruction will likely be introduced, even with maximum optimization turned on.Since all integers and longs are signed in the JVM, this makes the high order bit awkward to work with in Clojure. Unlike Java, all integral numbers are assumed to be
long
, so there is no special syntax to indicate this. And when numbers get large enough, they automatically roll over intoBigInt
values.Consequently, even though Java can say:
Clojure does not have this option of indicating that number is a long (and hence negative because of the most significant bit):
(Note: the
N
indicates a BigInt value)So we need to use the 2s complement form, and negate the value:
Simple Python solution, exploiting that any_even has a nice recursive case.
Note that if you know the size of an integer you could do this with bitmasking, so languages like C have much more efficient (and somewhat less interesting) solutions. Languages with unbounded ints (like Python) obviously can't do this.
Here is my solution with Python:
Go
Tests
Solution in nim:
Simple Python solution
JS one liner