-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_binary.php
75 lines (63 loc) · 1.32 KB
/
find_binary.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Validate console input
*
* Die if input is not valid
*
* @param array $argv user inputs
*/
function validateInput($argv)
{
$isValid = (count($argv) === 2);
if (!$isValid) {
echo 'php explore_url <integer>' . PHP_EOL;
die(1);
}
$int = intval($argv[1]);
if (0 == $int) {
echo 'Not an (not null) integer: ' . $argv[1] . PHP_EOL;
die(1);
}
}
/**
* Compute all power of two inferior to $int
*
* @param int $int
*
* @return int[]
*/
function computeEligiblePowersOfTwo($int)
{
$start = 0;
$current = $start;
$result = [];
while ($current <= $int) {
$result[$current] = pow(2, $current);
$current++;
}
return $result;
}
validateInput($argv);
require 'Util/TextColorWriter.php';
$int = intval($argv[1]);
$eligiblePowersOfTwo = computeEligiblePowersOfTwo($int);
$result = array();
foreach ($eligiblePowersOfTwo as $exp => $power) {
if ($power & $int) {
$result[$exp] = $power;
}
}
// echo result
echo TextColorWriter::textColor('INTEGER ANALYSIS:', TextColorWriter::BASH_PROMPT_GREEN) . PHP_EOL;
echo $int . ' = ';
foreach ($result as $power) {
echo $power . ' + ';
}
echo '(0)';
echo PHP_EOL;
echo $int . ' = ';
foreach ($result as $exp => $power) {
echo '2^' . $exp . ' + ';
}
echo '(0)';
echo PHP_EOL;