Monday, July 14, 2014

Add two binary number in string format -- FB

Question:
You have two numbers decomposed in binary representation, write a function that sums them and returns the result.

Input: 100011, 100100
Output: 1000111

Answer
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

string addBinary(string a, string b){
int len1 = a.length();
int len2 = b.length();
int maxlen = max(len1,len2);
int minlen = min(len1,len2);

int vc = 0, va = 0, vb = 0;
char remain = '0';
string res;

for(int i= maxlen-1;i >=0;--i){
if(i >= maxlen - minlen){
va = len1 < len2 ? a[i-maxlen+len1]-'0'+0 : a[i]-'0'+0;
vb = len2 < len1 ? b[i-maxlen+len2]-'0'+0 : b[i]-'0'+0;
}
else{
   va = len1 > len2? a[i]-'0'+0 : 0;
vb = len2 > len1? b[i]-'0'+0 : 0;
}

int sum = va + vb + vc;
if(sum<2){
remain = sum - 0 + '0';
vc = 0;
}
else{
remain = sum -2 - 0 + '0';
   vc = 1;
}
res.insert(0,1,remain);
}
if(vc){
res.insert(0,1,'1');
}
return res;
}

int main(){
string a,b,c;
while(1){
cin>> a;
cin>> b;
c = addBinary (a,b);
   cout <<a<<endl<<b<<endl<<c<<endl;
}
return 0;
}

No comments:

Post a Comment