-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecibinaryNumbers.php
More file actions
73 lines (60 loc) · 1.89 KB
/
DecibinaryNumbers.php
File metadata and controls
73 lines (60 loc) · 1.89 KB
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
<?php
namespace Hackerrank\InterviewKit\DynamicProgramming;
class DecibinaryNumbers
{
protected $lastCalculated;
protected $decibinaryLookup;
public function __construct()
{
// load the first 2 numbers in lookup table
$this->decibinaryLookup = [
1 => 0, // 0
2 => 1 // 1
];
// set the last calculated number to 1
$this->lastCalculated = 1;
}
public function lookupDecibinaryNumbers($x)
{
if (count($this->decibinaryLookup) >= $x) {
return $this->decibinaryLookup[$x];
}
while (count($this->decibinaryLookup) < $x) {
$this->lastCalculated++;
$moreForms = $this->findDebicinaryRepresentation($this->lastCalculated);
foreach ($moreForms as $f) {
$this->decibinaryLookup[] = $f;
}
}
return $this->decibinaryLookup[$x];
}
protected function findDebicinaryRepresentation($x)
{
$xforms = [$x];
$digits = 2;
$divisor = 2;
while ($divisor <= $x) {
$xforms = array_merge($xforms, $this->decibinaryFormsOfXInDigits($x, $digits));
$divisor *= 2;
$digits += 1;
}
return $xforms;
}
protected function decibinaryFormsOfXInDigits($x, $digits = 1)
{
$forms = [];
$base = pow(2, $digits - 1);
for ($i = 1; $i * $base <= $x; $i++) {
$remainer = $x - ($i * $base);
if ($digits > 2) {
$lowerForms = $this->decibinaryFormsOfXInDigits($remainer, $digits - 1);
foreach ($lowerForms as $f) {
$forms[] = (int) ($i . str_pad($f, $digits - 1, '0', STR_PAD_LEFT));
}
}
$forms[] = $i * pow(10, $digits - 1) + ($x - ($i * $base));
}
sort($forms);
return $forms;
}
}