-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinaryGap.php
57 lines (45 loc) · 916 Bytes
/
BinaryGap.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
<?php
/**
* BinaryGap
*
* Find longest sequence of zeros in binary representation of an integer.
*/
include '../../Tests.class.php';
function solution($A) {
$maxGap = 0;
$gap = 0;
while($A > 0){
if($A % 2 == 0){
$A = (int)($A / 2);
}else{
break;
}
}
while($A > 0){
$gap = ($A % 2 == 0) ? $gap + 1 : 0;
$maxGap = ($maxGap < $gap) ? $gap : $maxGap;
$A = (int)($A / 2);
}
return $maxGap;
}
$test = new Tests('BinaryGap');
$A = 9;
$result = 2;
$test->run(array($A), $result);
$A = 529;
$result = 4;
$test->run(array($A), $result);
$A = 20;
$result = 1;
$test->run(array($A), $result);
$A = 15;
$result = 0;
$test->run(array($A), $result);
$name = 'example1';
$A = 1041;
$result = 5;
$test->run(array($A), $result, $name);
$name = 'example2';
$A = 15;
$result = 0;
$test->run(array($A), $result, $name);