I'm trying to create a simple program, which adds 2 binary numbers provided by the user. I'm trying not to use vectors and so I'm using strings. Here is the code I have got so far:
#include <iostream>
#include <string>
int getLonger(std::string a, std::string b) {
if ((a.size() - '0') >= (b.size() - '0'))
return 1;
else
return 2;
}
int main() {
std::string n, k, result;
std::cout << "Enter first number: ";
std::cin >> n;
std::cout << "Enter second number: ";
std::cin >> k;
for (int i = 0; i < (getLonger(n, k) == 1 ? n : k).size(); i++) {
if ((getLonger(n, k) == 1 ? k : n)[i]) {
if ((n[i] - '0') + (k[i] - '0') == 2)
result.insert(0, "10");
else
result.insert(0, std::to_string(n[i] - '0' + k[i] - '0'));
}
}
std::cout << result;
}
I'm doing a lot of std::string => int conversion, which I know isn't great, but that's not the problem for me right now. The code works fine on something like 100101 + 10101 = 111010, but fails on:
1010 + 11 = -24110 (should be 1101)
and
1 + 11 = 10 (should be 100)
The first problem that I think affects the calculation is doing the loop on the longer of 2 strings. The correct way would probably be to resize the smaller one by adding some characters.
The second one is my wrong addition of 10, when 1 + 1 = 2 - the program doesn't carry 1. I tried fixing it by using some if statements, but it didn't work correctly.
I used the following resource to understand binary addition: http://web.math.princeton.edu/math_alive/1/Lab1/BinAdd.html
How can I make my script work correctly?
getLongerfunctions seems odd. Whats the point of subtracting'0'from thestrings size?getLongermultiple times (twice in each loop), but you only need to call it once and store its result. It would be better to zero fill the shorter string, so you do not need to worry about different lenghts. Why don't you do the sum in the reverse order, and then you invert the result? That way, you don't need to worry about carriage (it should be a value that gets tested in each loop and added if needed). It might be a good exercise to read how real machines do it (recommended book: Code, by Charles Petzold)