-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.php
More file actions
52 lines (50 loc) · 1.18 KB
/
Copy pathAddBinary.php
File metadata and controls
52 lines (50 loc) · 1.18 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
<?php
namespace App;
/**
* Add Binary
*
* Given two binary strings a and b, return their sum as a binary string.
*
* Example 1:
* Input: a = "11", b = "1"
* Output: "100"
*
* Example 2:
* Input: a = "1010", b = "1011"
* Output: "10101"
*
* https://leetcode.com/problems/add-binary
*/
class AddBinary
{
/**
* @param string $a
* @param string $b
* @return string
*/
public function addBinary(string $a, string $b): string
{
$result = '';
$aReversed = array_reverse(str_split($a));
$bReversed = array_reverse(str_split($b));
$carry = 0;
for ($i = 0; $i < max(strlen($a), strlen($b)); $i++) {
$digitA = 0;
if (isset($aReversed[$i])) {
$digitA = (int) $aReversed[$i];
}
$digitB = 0;
if (isset($bReversed[$i])) {
$digitB = (int) $bReversed[$i];
}
$total = $digitA + $digitB + $carry;
$char = $total % 2;
$result = $char . $result;
$carry = (int) ($total / 2);
}
if ($carry > 0) {
$result = '1' . $result;
}
return $result;
}
}