This code is supposed to get two very big numbers and add them together. Just iostream and string library allowed.
Example input:
132163162986831298132869132968213689316298613298681329689312682136312621382931628613286831286921968312698312698132682136893162986832168312698132
8312961362983126893162986312986832196893126813268932169831268912869621386893126893126891326831268361298621398631286831269813268312698132689312683612986892136813268312698312698321686312986312986893216831268921368321698132689312698132689321683126893216986893216893126813268931286931629886312
Example output:
8312961362983126893162986312986832196893126813268932169831268912869621386893126893126891326831268361298621398631286831269813268312698132689312683745150055123644566445567445666535375629284926285574546520581603504634319515620941311419520608605095205915299591349575263706431918119099942584444
#include <iostream>
#include <string>
using namespace std;
int main (){
string num1 , num2 ,sum;
getline(cin,num1);
getline(cin,num2);
if (num2.length() > num1.length())
{
num2.swap(num1);
}
std::reverse(num1.begin(), num1.end());
std::reverse(num2.begin(), num2.end());
while(num2.length() < num1.length())
num2.push_back('0');
size_t lnth = num1.length();
unsigned tmp , holder=0;
for (size_t i = 0;i < lnth ; i ){
tmp = (num1[i] - '0') (num2[i] - '0') holder;
sum.push_back(tmp % 10 '0');
holder = tmp / 10;
}
if(holder > 0){
sum.push_back('0' holder);
}
while(!sum.empty()){
if (sum[sum.length() - 1] == '0'){
sum.pop_back();
}
else{
break;
}
}
std::reverse(sum.begin(), sum.end());
cout << sum;
}
I' getting some correct and some wrong answers;
CodePudding user response:
To begin with, given size_t i
, the condition i >= 0
is always true by definition.
This is because size_t
yields a 2s-complement unsigned representation.
Therefore, the loop for (size_t i = whatever; i >= 0; i--)
will just run forever, or until "something bad happens".
CodePudding user response:
Did you know std::string
has a wonderful feature called "reverse iterators"?
It makes your life a whole lot easier:
auto it1 = str1.crbegin(), it2 = str2.crbegin();
int carry = 0;
std::string result;
while (it1 != str1.crend() && it2 != str2.crend()) {
int sum = (*it1 - '0') (*it2 - '0') carry;
result.push_back('0' (sum % 10));
carry = sum / 10;
it1 ; it2 ;
}
// We assume str1 is the longest, so copy digits from str1
while (it1 != str1.crend()) {
int sum = (*it1 - '0') carry;
result.push_back('0' (sum % 10));
carry = sum / 10;
it1 ;
}
// This is an edge case: if str1.length == str2.length, carry might be 1
if (carry) {
result.push_back('1');
}
// Reverse result
result = std::string(result.crbegin(), result.crend());