-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.php
More file actions
42 lines (37 loc) · 1.14 KB
/
binary.php
File metadata and controls
42 lines (37 loc) · 1.14 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
<?php
function addOneToBinary($binaryStr) {
// Initialize the result string and carry
$result = '';
$carry = 1; // We are adding one, so the initial carry is 1
// Loop through the binary string from the end to the beginning
for ($i = strlen($binaryStr) - 1; $i >= 0; $i--) {
$char = $binaryStr[$i];
if ($char == '0') {
if ($carry) {
$result = '1' . $result;
$carry = 0;
} else {
$result = '0' . $result;
}
} else { // $char == '1'
if ($carry) {
$result = '0' . $result;
$carry = 1; // Still need to carry over
} else {
$result = '1' . $result;
}
}
}
// If there's still a carry left after the loop, prepend '1' to the result
if ($carry) {
$result = '1' . $result;
}
return $result;
}
// Input from the user
echo "Enter a binary string: ";
$handle = fopen("php://stdin", "r");
$n = trim(fgets($handle));
fclose($handle);
$result = addOneToBinary($n);
echo "The binary representation of $n + 1 is $result\n";