## Interview Question

Software Engineer Interview

# Add two binary numbers (Input as a string)

1

public static void main(String[] args){
int sum = sumTwoBinaries("10101", "110101");
System.out.println("sum is : " + sum + " or " + Integer.toString(sum, 2));
}

public static int sumTwoBinaries(String b1, String b2){

int i1 = Integer.parse(b1, 2);
int i2 = Integer.parse(b2, 2);

return i1 + i2;

}

Genc on Aug 13, 2014
8

Pretty certain this question would require you to not use a built-in integer parser.

BW on Aug 13, 2014
0

#include
#include
#include

char * add_numbers(char *num1, char *num2);

main()
{
char *num1 = "10001";
char *num2 = "00111";

printf ("num1 %s + num2 %s is %s ", num1, num2, add_numbers(num1, num2));

}

char * add_numbers(char *num1, char *num2)
{
char *num;
int len;
int carry = 0;

len = strlen( num1);
num = malloc (sizeof(char) * len);

len--; //offset

while (len &gt;= 0) {
if (num1[len] == '0' &amp;&amp; num2[len] == '0') {
num[len] = (carry) ? '1' : '0';
carry = 0;
} else if (num1[len] == '1' &amp;&amp; num2[len] == '1') {
num[len] = (carry) ? '1' : '0';
carry = 1;
} else if (num1[len] == '1' &amp;&amp; num2[len] == '0') {
if (carry) {
num[len] = '0';
carry = 1;
} else {
num[len] = '1';
}
} else if (num1[len] == '0' &amp;&amp; num2[len] == '1') {
if (carry) {
num[len] = '0';
carry = 1;
} else {
num[len] = '1';
}
}
len--;
}
return num;
}

casper on Aug 14, 2014
0

Answer by Casper is wrong in two aspects: first, it assumes that strings has equal length (which is very presumptions). And even doing that it doesn't account the case when both numbers start from 1 - for that the length of the resulting string will be bigger by 1.

Mikhail on Aug 23, 2014
0

private static String calcBinaryAdd (String num1, String num2)
{
int length = 0;
int numIndex = 0;
int sum = 0;
int carry = 0;

if(num1.length() &gt; num2.length())
{
length = num1.length();
}
else if (num2.length() &gt; num1.length())
{
length = num2.length();
}
else
{
length = num1.length();
}
int [] numArray1 = new int[length];
int [] numArray2 = new int[length];
int [] answerArray = new int [numArray1.length + 1];

populateArray(num1, numArray1);
populateArray(num2, numArray2);

while(numIndex &gt; 0)
{
sum = numArray1[numIndex-1] + numArray2[numIndex-1] + carry;

if(sum &gt; 1)
{
carry = sum / 2;
sum = sum % 2;
}
else
{
carry = 0;
}

numIndex--;
}

}

private static void populateArray (String num, int[] numArray)
{
for(int i = num.length()-1; i&gt;=0; i--)
{
numArray[i+ (numArray.length-num.length())] = num.charAt(i) - '0';
}
}

Anonymous on Sep 12, 2014
0

int carry=0;
StringBuilder sb=new StringBuilder();
Stacks=new Stack();
int sLoop=Integer.max(n1.length(),n2.length());
for(int i=0;ii)v+=n1.charAt(n1.length()-1-i)-'0';
if(n2.length()&gt;i)v+=n2.charAt(n2.length()-1-i)-'0';
v+=carry;
carry=v/2;
}
while(!s.isEmpty())sb.append(s.pop());
return sb.toString();
}

Anonymous on Sep 22, 2014
0

public static int addBinary(String binary1, String binary2) {
int binary1Integer = 0;
int binary2Integer = 0;

for (int i = binary1.length() - 1; i &gt;= 0; i--)
if (binary1.charAt(i) == '1') {
binary1Integer += Math.pow(2, binary1.length()-i-1);
}

for (int i = binary2.length() - 1; i &gt;= 0; i--) {
if (binary2.charAt(i) == '1')
binary2Integer += Math.pow(2, binary2.length()-i-1);
}

return binary1Integer + binary2Integer;
}

I wasn&#039;t sure if the answer was supposed to be in binary or not, but here is in base 10 on Sep 28, 2014
0

#include
using namespace std;

char addBits (char c1, char c2, bool &amp;carry);
string sumBinary (string s1, string s2);

int main() {

cout len2 ? s1: s2;

int len3 = s3.length() -1;

bool carry = false;

while (len1&gt;=0 || len2&gt;=0) {

char b1 = len1&gt;=0? s1[len1--]: '0';
char b2 = len2&gt;=0? s2[len2--]: '0';

if (b1 &gt; '1' || b1 '1' || b2 &lt; '0') {
cout &lt;&lt; "invalid character";
return "";
}

}
if (carry)
s3 = "1" + s3;

return s3;
}

char addBits (char c1, char c2, bool &amp;carry)
{
char rc;

int i1 = c1=='0'? 0:1;
int i2 = c2=='0'? 0:1;
int ic = carry ? 1: 0;

int sum = i1 + i2 +ic;

switch (sum) {
case 3:
carry = true;
rc = '1';
break;
case 2:
carry = true;
rc = '0';
break;
case 1:
carry = false;
rc = '1';
break;
default:
rc = '0';
}

return rc;

}

Ankur on Dec 24, 2014
0

#include
using namespace std;

string sumBinary (string s1, string s2);

int main() {

cout len2 ? s1: s2;

int len3 = s3.length() -1;

bool carry = false;

while (len1&gt;=0 || len2&gt;=0) {

int i1 = len1&gt;=0? s1[len1--] - '0': 0;
int i2 = len2&gt;=0? s2[len2--] - '0': 0;

// Check if any invalid character
if (i1 1 || i21)
return "";

// 3 bit sum
int sum = i1 ^ i2 ^ carry;

// 3 bit carry
carry = (i1 &amp; carry) | (i2 &amp; carry) | (i1 &amp; i2);

s3[len3--] = '0' + sum;

}

if (carry)
s3 = "1" + s3;

return s3;
}

AV on Dec 24, 2014
0

Add two binary numbers (Input as a string)

int strToNum(string a)
{
int res = 0;
for( int i=a.length()-1;i&gt;=0;i--)
res += (1&lt;

Guy on Jul 23, 2018
0

// Not using any built-in libraries

// Emulate a binary full adder
const addBits = (a, b, c) =&gt; {
switch(`\${a}\${b}\${c}`) {
case '000':
return { sum: '0', carry: '0' };
case '001':
case '010':
case '100':
return { sum: '1', carry: '0' };
case '011':
case '101':
case '110':
return { sum: '0', carry: '1' };
case '111':
return { sum: '1', carry: '1' };
}
};

const sum = (a, b) =&gt; {
let longNum = a.split('').reverse();
let shortNum = b.split('').reverse();
const sum = [];
let carry = 0;
let i;

for(i = 0; i &lt; shortNum.length; i++) {
const result = addBits(longNum[i], shortNum[i], carry);

sum.unshift(result.sum);
carry = result.carry;
}

for(;i &lt; longNum.length; i++) {
const result = addBits(longNum[i], '0', carry);

sum.unshift(result.sum);
carry = result.carry;
}

if (carry === '1') {
sum.unshift(carry);
}

return sum.join('');
}

console.log(sum('1111', '1'));

Anonymous on Jul 28, 2018
0

Seeing so many ugly answers here's mine in JavaScript ES6 (let, const, arrow functions) I did in 15 minutes on paper to start.

const binaryAdd = (s1, s2) =&gt; {
const longer = Math.max(s1.length, s2.length);
let finalSum = 0;
let carry = 0;

for (let index = 0; index = 2) {
carry = 1;
} else {
carry = 0;
}
finalSum += sum % 2 ? 2 ** index : 0;
}
if (carry) {
finalSum += 2 ** longer;
}
return finalSum;
};

Anonymous on Mar 11, 2019
0

Here's my one line python solutions

class Solution(object):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a,2) + int(b,2))[2:]

class Solution(object):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(eval['0b' + a) + eval['0b' + b))[2:]

Ankit Shah on Mar 14, 2019

One or more comments have been removed.