Reputation: 43
I have a problem with adding 2 binary numbers. I want to do this as a string, so if they're different lengths I concatenate '0' to the beginning of shorter string. First of all, I don't know why, but I need to substrate then add '0' (without it, it wasn't working at all).
#include <iostream>
using namespace std;
string add( string no1, string no2 );
int equalizer(string no1, string no2)
{
int len1 = no1.length();
int len2 = no2.length();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
{
no1 = '0' + no1;
}
return len2;
}
else if (len1 >= len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
{
no2 = '0' + no2;
}
return len1; // If len1 >= len2
}
}
string add( string no1, string no2 )
{
string result="";
int length = equalizer(no1, no2);
int carry = 0;
for (int i = length-1 ; i >= 0 ; i--)
{
int bit1 = no1.at(i) - '0';
int bit2 = no2.at(i) - '0';
// boolean expression for sum of 3 bits
int sum = (bit1 ^ bit2 ^ carry)+'0';
result = (char)sum + result;
// boolean expression for 3-bit addition
carry = (bit1 & bit2) | (bit2 & carry) | (bit1 & carry);
}
// if overflow, then add a leading 1
if (carry)
{
result = '1' + result;
}
return result;
}
bool check(string no1)
{
for(int i =0; i<no1.length(); i++)
{
if(no1.at(i)!=0 || no1.at(i)!=1)
{
cout << "not biniary! should contain only '0' and '1' "<< endl;
return false;
}
else
{
return true;
}
}
}
int main()
{
string no1;
string no2;
cout << "Welcome to program that add 2 biniary numbers!" << endl;
cout <<"Give first number " <<endl;
cin >> no1;
if(check(no1)==true)
{
cout <<"Give 2nd number" << endl;
cin >> no2;
check(no2);
cout << "Numbers are proper!" << endl;
add(no1,no2);
}
else
{
cout <<"End of program."<<endl;
}
return 0;
}
Upvotes: 0
Views: 2360
Reputation: 3725
I think the following code can be helpful.
int getBit(string s, int index)
{
if(index >= 0) return (s[index] - '0');
else return 0;
}
string addBinary(string a, string b)
{
if(a.size() > b.size()) while(a.size() > b.size()) b = "0" + b;
else if(b.size() > a.size()) while(b.size() > a.size()) a = "0" + a;
int l = max(a.size()-1, b.size() - 1);
string result = "";
int s=0;
while(l>=0 || s==1)
{
s += getBit(a, l) + getBit(b, l) ;
result = char(s % 2 + '0') + result;
s /= 2;
l--;
}
return result;
}
Upvotes: 0
Reputation: 49
use this method to add 0s in the beginning:-
considering that your str1 goes out of scope and str2 remains and you want to add str1 before str2
char *temp = strdup(str2);
strcpy(str2, str1);
strcat(str2, temp);
free(temp);
Upvotes: 0
Reputation: 13988
Instead of adding trailing zeros I would reverse the string at the beggining: std::reverse(s1.begin(), s1.end())
. Then I would add each digit from the beggining. res[i] = s1[i] - s2[i] + '0';
Remember to initialize res string and then reverse it back again! Good luck!
Upvotes: 1