Given two binary strings, return their sum (also a binary string).
Example:
Input: a = "11", b = "1"
Output: "100"
We strongly recommend you to minimize your browser and try this yourself first
The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits.
C++
#include <bits/stdc++.h>
using namespace std;
string addBinary(string A, string B)
{
if (A.length() > B.length())
return addBinary(B, A);
int diff = B.length() - A.length();
string padding;
for ( int i = 0; i < diff; i++)
padding.push_back( '0' );
A = padding + A;
string res;
char carry = '0' ;
for ( int i = A.length() - 1; i >= 0; i--) {
if (A[i] == '1' && B[i] == '1' ) {
if (carry == '1' )
res.push_back( '1' ), carry = '1' ;
else
res.push_back( '0' ), carry = '1' ;
}
else if (A[i] == '0' && B[i] == '0' ) {
if (carry == '1' )
res.push_back( '1' ), carry = '0' ;
else
res.push_back( '0' ), carry = '0' ;
}
else if (A[i] != B[i]) {
if (carry == '1' )
res.push_back( '0' ), carry = '1' ;
else
res.push_back( '1' ), carry = '0' ;
}
}
if (carry == '1' )
res.push_back(carry);
reverse(res.begin(), res.end());
int index = 0;
while (index + 1 < res.length() && res[index] == '0' )
index++;
return (res.substr(index));
}
int main()
{
string a = "1101" , b = "100" ;
cout << addBinary(a, b) << endl;
return 0;
}
|
Java
public class GFG {
static String addBinary(String A, String B)
{
int i = A.length()- 1 ;
int j = B.length()- 1 ;
int carry = 0 ;
int sum = 0 ;
StringBuilder result = new StringBuilder();
while (i>= 0 || j>= 0 || carry == 1 ){
sum = carry;
if (i>= 0 ) sum = sum+A.charAt(i)- '0' ;
if (j>= 0 ) sum = sum+B.charAt(j)- '0' ;
result.append(( char )(sum% 2 + '0' ));
carry = sum/ 2 ;
i--;
j--;
}
return result.reverse().toString();
}
public static void main(String args[])
{
String a = "1101" , b= "100" ;
System.out.print(addBinary(a, b));
}
}
|
Python3
def add_binary_nums(x, y):
max_len = max ( len (x), len (y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range (max_len - 1 , - 1 , - 1 ):
r = carry
r + = 1 if x[i] = = '1' else 0
r + = 1 if y[i] = = '1' else 0
result = ( '1' if r % 2 = = 1 else '0' ) + result
carry = 0 if r < 2 else 1
if carry ! = 0 : result = '1' + result
return result.zfill(max_len)
print (add_binary_nums( '1101' , '100' ))
|
C#
using System;
class GFG {
static string addBinary( string a,
string b)
{
string result = "" ;
int s = 0;
int i = a.Length - 1, j = b.Length - 1;
while (i >= 0 || j >= 0 || s == 1)
{
s += ((i >= 0)? a[i] - '0' : 0);
s += ((j >= 0)? b[j] - '0' : 0);
result = ( char )(s % 2 + '0' ) + result;
s /= 2;
i--; j--;
}
return result;
}
public static void Main()
{
string a = "1101" , b= "100" ;
Console.Write( addBinary(a, b));
}
}
|
PHP
<?php
function addBinary( $a , $b )
{
$result = "" ;
$s = 0;
$i = strlen ( $a ) - 1;
$j = strlen ( $b ) - 1;
while ( $i >= 0 || $j >= 0 || $s == 1)
{
$s += (( $i >= 0)? ord( $a [ $i ]) -
ord( '0' ): 0);
$s += (( $j >= 0)? ord( $b [ $j ]) -
ord( '0' ): 0);
$result = chr ( $s % 2 + ord( '0' )) . $result ;
$s = (int)( $s / 2);
$i --; $j --;
}
return $result ;
}
$a = "1101" ;
$b = "100" ;
echo addBinary( $a , $b );
?>
|
Javascript
<script>
function addBinary(a, b)
{
var result = "" ;
var s = 0;
var i = a.length - 1, j = b.length - 1;
while (i >= 0 || j >= 0 || s == 1)
{
s += ((i >= 0)? a.charAt(i).charCodeAt(0) -
'0' .charCodeAt(0): 0);
s += ((j >= 0)? b.charAt(j).charCodeAt(0) -
'0' .charCodeAt(0): 0);
result = String.fromCharCode(parseInt(s % 2) +
'0' .charCodeAt(0)) + result;
s = parseInt(s/2);
i--; j--;
}
return result;
}
var a = "1101" , b= "100" ;
document.write(addBinary(a, b));
</script>
|
Time Complexity: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively.
Auxiliary Space: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!