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