Today I tried solving this problem on SPOJ, in which you reverse the digits of two numbers, add them, and print the reversed digits of the sum. (When reversing, leading zeroes in the result should be dropped, and trailing zeroes in the result shouldn't happen.)
I used C++ to write the code for this problem. My code got accepted in the first go and I was happy about it but I feel my code is way too long for a problem of this kind. I would like some suggestions on how to reduce the code and make it more readable at the same time.
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
using namespace std;
#define ALL(C) (C).begin(), (C).end()
#define LN(str) (int)(str).length()
// this function gets the reversed form of the input number, the function is coded assuming that the input number has both trailing and leading 0's
string getReverseNum(string& num) {
string reversedNum = "";
// find the index of last leading 0
int index1 = -1;
for(int i = 0; i < LN(num); ++i) {
if(num[i] == '0')
continue;
else {
index1 = i;
break;
}
}
// find the index of the first trailing 0
int index2 = -1;
for(int i = LN(num)-1; i >= 0; --i) {
if(num[i] == '0')
continue;
else {
index2 = i+1;
break;
}
}
reversedNum = num.substr(index1, index2-index1);
if(reversedNum == "")
return "0";
return reversedNum;
}
// this function is used to convert an integer to a string
string convertIntToString(int num) {
ostringstream oss;
oss << num;
return oss.str();
}
// this function is used to add the two input numbers and return the result as a string
string addNumbers(string& num1, string& num2) {
int carry = 0;
string result = "";
for(int i = 0; i < LN(num2); ++i) {
int dig1 = num1[i]%48;
int dig2 = num2[i]%48;
int temp = dig1+dig2+carry;
carry = temp/10;
result += convertIntToString(temp%10);
}
for(int i = LN(num2); i < LN(num1); ++i) {
int dig = num1[i]%48;
int temp = dig+carry;
carry = temp/10;
result += convertIntToString(temp%10);
}
if(carry != 0)
result += convertIntToString(carry);
return getReverseNum(result);
}
// this function is used to return the reversed sum of the two input numbers it receives as parameters
string getReversedSum(string& num1, string& num2) {
// first we get the reverse of two numbers
string reversedNum1 = getReverseNum(num1);
string reversedNum2 = getReverseNum(num2);
string reversedNum = "";
int len1 = LN(reversedNum1), len2 = LN(reversedNum2);
if(len1 < len2)
return addNumbers(reversedNum2, reversedNum1);
return addNumbers(reversedNum1, reversedNum2);
}
int main() {
// this variable stores the number of test cases on which the program is run
int N;
cin >> N;
// clear the input stream
cin.ignore();
// program execution begins here
while(N--) {
string num1, num2;
cin >> num1 >> num2;
cout << getReversedSum(num1, num2) << endl;
}
return 0;
}
Code is hosted here.