-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_gap.php
47 lines (34 loc) · 877 Bytes
/
binary_gap.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
<?php
error_reporting(-1); // show error messages
$N = 1041;
echo "n:".$N."<br>";
$bin = decbin($N);
echo "bin: ".$bin."<br>";
echo "Result: ".getMaxBinaryGap($N);
function getMaxBinaryGap($N) {
while ($N > 0 && ($N & 1) == 0) { // shift until we get 1 on the right
$N = $N >> 1;
echo "shifted: ".decbin($N)."<br>";
$rightbit = $N & 1;
echo $rightbit."<br>";
}
$N = $N >> 1; //popoff the 1 on the right
$count = $maxCount = 0;
while ($N > 0 ) {
while (($N & 1) == 0) { // shift until we get 1 on the right
$N = $N >> 1;
echo "shifted: ".decbin($N)."<br>";
$rightbit = $N & 1;
echo $rightbit."<br>";
$count++;
}
echo "count = ".$count."<br>";
if ($count > $maxCount) { //update max count
$maxCount = $count;
}
$count = 0; //reset
$N = $N >> 1; //popoff the 1 on the right, and go again
}
return $maxCount;
}
?>