HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Adding Reversed Numbers - ADDREV on SPOJ

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbersreversedspojaddingaddrev

Problem

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
#include
#include
#include
#include
#include
#include

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 = 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 > 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.

Solution

A few notes:

-
Why do you have a bunch of extra headers at the top? This extra cruft (such as the vector class), is going to cost you a bit of extra compile time for nothing plus it adds to the length of your code. Cut back on the stuff you don't need; I found you only needed two of the headers out of the seven you have in your code.

-
Here are the woes of using namespace std;. Please try to get into the habit of not using it.

-
Your #define's are interesting, but I found them a bit useless really. They somewhat obscure the readability of the program as well, and should be removed IMO.

-
Your getReverseNum() function really just reverses a std::string object... but there's a standard library function std::reverse() that does this task for you (it's likely that this function is more efficient as well).

-
In C++, you should almost never use out parameters (variables taken by reference and used to return a value from a function), you can read this excellent article by Eric Niebler. There are few cases where out parameters can make sense:

-
When you want your return to be fast. And even then, return value optimization and move semantics may still be faster.

-
When you have several output values. For example, you want to assign a value to a function and return whether it succeeded:

bool assign(int from, int& to)
{
    if (from != 0)
    {
        to = from;
        return true;
    }
    return false;
}


But even for this situation, there are better solutions such as boost:optional to return both a value and whether it succeeded or not. And if you need several error values, use exceptions. And if you need to actually return several values, you general want to pack them into a dedicated struct or a std::tuple.

-
Input-output parameters: sometimes, you want to take a parameter, read from it, and then write to it again. That is still a valid use case (but these are not strict out parameters anymore).

Overall, for your case it would be better to remove the reference parameters as they serve no purpose really and could be hurting performance.

-
Your addNumbers() function could be simplified with the use of the standard functions std::stoi, std::to_string, and std::string::erase, along with our old friend std::reverse.

-
Your variable N in your main() function is somewhat confusing as to what it's purpose is at first. I found it better named as cases.

Final Code:

#include 
#include 

std::string getReversedSum(std::string num1, std::string num2)
{
    // first we reverse the two numbers
    std::reverse(std::begin(num1), std::end(num1));
    std::reverse(std::begin(num2), std::end(num2));

    // convert the strings to ints so we can add them, then back to a string
    std::string sum = std::to_string(std::stoi(num1) + std::stoi(num2));

    // reverse the string and erase the leading zeros
    std::reverse(std::begin(sum), std::end(sum));
    sum.erase(0, sum.find_first_not_of('0'));
    return sum;
}

int main()
{
    int cases = 0;
    std::cin >> cases;

    // clear the input stream
    std::cin.ignore();

    while(cases--)
    {
        std::string num1;
        std::string num2;
        std::cin >> num1 >> num2;
        std::cout << getReversedSum(num1, num2) << std::endl;
    }
}

Code Snippets

bool assign(int from, int& to)
{
    if (from != 0)
    {
        to = from;
        return true;
    }
    return false;
}
#include <string>
#include <iostream>

std::string getReversedSum(std::string num1, std::string num2)
{
    // first we reverse the two numbers
    std::reverse(std::begin(num1), std::end(num1));
    std::reverse(std::begin(num2), std::end(num2));

    // convert the strings to ints so we can add them, then back to a string
    std::string sum = std::to_string(std::stoi(num1) + std::stoi(num2));

    // reverse the string and erase the leading zeros
    std::reverse(std::begin(sum), std::end(sum));
    sum.erase(0, sum.find_first_not_of('0'));
    return sum;
}

int main()
{
    int cases = 0;
    std::cin >> cases;

    // clear the input stream
    std::cin.ignore();

    while(cases--)
    {
        std::string num1;
        std::string num2;
        std::cin >> num1 >> num2;
        std::cout << getReversedSum(num1, num2) << std::endl;
    }
}

Context

StackExchange Code Review Q#91504, answer score: 8

Revisions (0)

No revisions yet.