Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bba3990

Browse files
committed
Add decomposition into powers of two script
1 parent 3cdd1f6 commit bba3990

File tree

2 files changed

+84
-1
lines changed

2 files changed

+84
-1
lines changed

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,12 @@ php get_by_sql_value.php inputFile outputFile
4545
```
4646
Read input file, get lines from an SQL table from file1 value, write lines into output file
4747

48-
Add settings/credentials in a config.php file to run it
48+
Add settings/credentials in a config.php file to run it
49+
50+
find_binary
51+
-----------
52+
53+
```bash
54+
php find_binary.php <integer>
55+
```
56+
Decompose an integer into powers of two

‎find_binary.php‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /