I´m trying to break a number into an array of numbers (in php) in the way that for example:
- 25 becomes (16, 8, 1)
- 8 becomes (8)
- 11 becomes (8, 2, 1)
I don´t know what the correct term is, but I think the idea is clear.
My solution with a loop is pretty straightforward:
$number = rand(0, 128);
$number_array_loop = array();
$temp_number = $number;
while ($temp_number > 0) {
$found_number = pow(2, floor(log($temp_number, 2)));
$temp_number -= $found_number;
$number_array_loop[] = $found_number;
}
I also have a recursive solution but I can´t get that to work without using a global variable (don´t want that), the following comes close but results in arrays in arrays:
function get_numbers($rest_number) {
$found_number = pow(2, floor(log($rest_number, 2)));
if ($found_number > 0) {
$temp_array[] = get_numbers($rest_number - $found_number);
$temp_array[] = $found_number;
}
return $temp_array;
}
$number_array_recursive = array();
$number_array_recursive = get_numbers($number);
However, using something like pow(floor(log())) seems a bit much for a simple problem like this.
It seems to me that the problem calls for a recursive solution with some very simple maths, but I just don´t see it.
Any help would be apreciated.
Edit: Binary is the key, thanks a lot all!