4
\$\begingroup\$

I've finished ADDREV challenge but I'm still not happy with my current solution. How can I still make my solution efficient without using the built-in std::reverse() function?

The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

Input

The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

Output

For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

#include<string>
#include<iostream>

int reverse(int num);
int main() {
int n, a, b;

scanf_s("%d", &n);
while (n--) {
    std::cin >> a;
    std::cin >> b;
    //reverse the two number
    int sum = reverse(a) + reverse(b);
    sum = reverse(sum);

   //convert sum to string in order to remove zeroes 
    std::string sumString = std::to_string(sum);
    sumString.erase(0, sumString.find_first_not_of('0'));
    std::cout << sumString;
}
    system("PAUSE");
    return 0;
}

int reverse(int num) {
   std::string r = std::to_string(num);
   std::string tmp;
   for (int i = r.length(); i >= 0; i--)
     {
       tmp = tmp + r.substr(i, 1);
     }
  return std::stoi(tmp);
}
\$\endgroup\$
1
  • \$\begingroup\$ Is the strange indentation of main() a real thing in your code, or a markdown problem when posting the code? You're still able to fix this without affecting any answers. \$\endgroup\$ Mar 16, 2017 at 11:46

2 Answers 2

4
\$\begingroup\$

Here's one way to reverse numbers without converting to strings and/or using std::reverse. As per the challenge, this deals with only positive integers.

int RevNum( int num )
{
    int outVal = 0;
    while ( num > 0 )
    {
        int temp = num % 10;
        outVal = ( outVal * 10 ) + temp;
        num /= 10;
    }
    return outVal;
}

Because the number starts and stays as a number, zeros are automatically handled properly.

\$\endgroup\$
2
\$\begingroup\$

This fails to compile for me as C++17:

157770.cpp: In function ‘int main()’:
157770.cpp:9:21: error: ‘scanf_s’ was not declared in this scope
     scanf_s("%d", &n);
                     ^

If that was a typo for scanf (or an attempt to use C11 scanf_s¹), then you ought to check the result, to verify that you did read exactly one value:

if (std::scanf("%d", &n) != 1) {
    std::cerr << "Expected count of inputs" << std::endl;
    return EXIT_FAILURE;
}

You'll need to include <cstdio> for std::scanf and <cstdlib> for EXIT_FAILURE.

Simpler is to use std::cin, as for the subsequent reads:

std::cin >> n;
if (!std::cin) {
    std::cerr << "Expected count of inputs" << std::endl;
    return EXIT_FAILURE;
}

In passing, I'll note that n can't be negative, so consider using an unsigned type.

¹ If you were looking for the C11 function, there's no need in this case, as you don't use %c, %s or %[, meaning that plain scanf() is perfectly safe.


In the loop, we should check that we could successfully read inputs:

    std::cin >> a >> b;
    if (!std::cin) {
        std::cerr << "Failed to read input value" << std::endl;
        return EXIT_FAILURE;
    }

The specification says the numbers won't be negative, so a and b can be unsigned. Their scope can be reduced to within the loop.


You strip leading zeros twice: once by converting back to int and then again with string::erase(). You only need one of those:

    int sum = reverse(a) + reverse(b);
    std::cout << reverse(sum) << '\n';

I've added a newline there, to match the challenge requirements of one result per line.


After the loop, you have

system("PAUSE");
return 0;

It's obviously non-portable to rely on a program (PAUSE) that most systems don't have. I'm guessing it's not important, as you don't check the return value. See "system(“pause”); - Why is it wrong?" Normally it's best to just print the output and return. The return 0; isn't necessary in main(), though it does no harm. You can safely omit it.


The reverse() method works with strings; it's probably faster to use decimal arithmetic:

int reverse(int num) {
    int result = 0;
    while (num) {
        result *= 10;
        result += num % 10;
        num /= 10;
    }
    return result;
}

Modified code

#include<string>
#include<iostream>
#include<cstdlib>

using value_type = unsigned long;

value_type reverse(value_type num) {
    value_type result{};
    while (num) {
        result *= 10;
        result += num % 10;
        num /= 10;
    }
    return result;
}

int main() {
    unsigned int n;
    std::cin >> n;
    if (!std::cin) {
        std::cerr << "Expected count of inputs" << std::endl;
        return EXIT_FAILURE;
    }

    while (n--) {
        value_type a, b;
        std::cin >> a >> b;
        if (!std::cin) {
            std::cerr << "Failed to read input value" << std::endl;
            return EXIT_FAILURE;
        }
        auto sum = reverse(a) + reverse(b);
        std::cout << reverse(sum) << '\n';
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.