33
9
Yesterday while playing with my kid I noticed the number in his toy train:
So we have $$4281$$ that can be split into $$4-2-8-1$$ or $$2^2-2^1-2^3-2^0$$
So simple challenge: given a non-negative number as input, return consistent truthy and falsey values that represent whether or not the string representation of the number (in base 10 and without leading zeroes) can be somehow split into numbers that are powers of 2.
Examples:
4281 truthy (4-2-8-1)
164 truthy (16-4 or 1-64)
8192 truthy (the number itself is a power of 2)
81024 truthy (8-1024 or 8-1-02-4)
101 truthy (1-01)
0 falsey (0 cannot be represented as 2^x for any x)
1 truthy
3 falsey
234789 falsey
256323 falsey (we have 256 and 32 but then 3)
8132 truthy (8-1-32)
Tests for very large numbers (not really necessary to be handled by your code):
81024256641116 truthy (8-1024-256-64-1-1-16)
64512819237913 falsey
This is code-golf, so may the shortest code for each language win!
2@StewieGriffin initially I thought about limiting the input number to the range of a standard
int
type (4 bytes), but actually I do not mind if your code does not support very large numbers. Just state in your answer the limitations of your code. – Charlie – 2018-10-11T08:03:48.5073Suggested test case:
101
(falsy because of the 0) ... or should this still be true (1 - 01
)? – Shieru Asakoto – 2018-10-11T08:17:52.8831@ShieruAsakoto I've been testing the
101
case with the current answers and they all returntrue
, because it can be splitted into1-01
that are both powers of 2, so I'll consider that case to be truthy. – Charlie – 2018-10-11T08:21:00.3136Just leaving this here as tip for everyone. Here are three possible ways to check if a number is a power of 2: 1) Check if
log2(n)
doesn't contain decimal digits after the comma. 2) Check ifn AND (n-1) == 0
. 3) Create a list of square-nrs and check ifn
is in that list. – Kevin Cruijssen – 2018-10-11T08:37:00.3601"square-nrs" should be "powers of 2" in my comment above of course.. >.> – Kevin Cruijssen – 2018-10-11T14:00:40.897
1Related – hakr14 – 2018-10-11T17:20:53.370
Similar question – nwellnhof – 2018-10-11T23:55:23.323
Should the code only work for powers of 2 that are a natural number? Like, 0.25 = 2^-2? – Nzall – 2018-10-12T09:37:37.840
@Nzall no, only non-negative integers are needed for this challenge. – Charlie – 2018-10-12T09:56:09.183
Actually,
01
is not a proper number. – Titus – 2018-10-12T12:46:10.717