-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertToBase2.php
More file actions
55 lines (49 loc) · 1.03 KB
/
Copy pathConvertToBase2.php
File metadata and controls
55 lines (49 loc) · 1.03 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
<?php
namespace App;
/**
* Convert to Base -2
*
* Given an integer n, return a binary string representing its representation in base -2. Note that the returned string
* should not have leading zeros unless the string is "0".
*
* Example 1:
* Input: n = 2
* Output: "110"
* Explanation: (-2)2 + (-2)1 = 2
*
* Example 2:
* Input: n = 3
* Output: "111"
* Explanation: (-2)2 + (-2)1 + (-2)0 = 3
*
* Example 3:
* Input: n = 4
* Output: "100"
* Explanation: (-2)2 = 4
*
* https://leetcode.com/problems/convert-to-base-2
*/
class ConvertToBase2
{
/**
* @param int $num
* @return string
*/
public function baseNeg2(int $num): string
{
if ($num === 0) {
return '0';
}
$result = '';
while ($num !== 0) {
$remainder = $num % -2;
$num = intdiv($num, -2);
if ($remainder < 0) {
$remainder += 2;
++$num;
}
$result = $remainder . $result;
}
return $result;
}
}