Adding reversed numbers

One of the most popular SPOJ classical problems is number 42 (a good one indeed), namecode ADDREV, that is about reverting numbers.

We are asked to read couples of (small) positive integers, revert them, add them up, revert the result and return it.

So, if we get in input 24 and 1, we should add 42 and 1, and return 34. Easy, isn't it?

There shouldn't be any issue on solving this problem. In any case, here is a possible implementation for its central part, a function (so simple that I have wrote it thinking in C++, but for the reader it could be C/C++, Java, and easily ported in many other languages with minimal, if any, changes) that gets in input a integer and returns it reverted:
int revert(int input) // 1
{
    int result = 0;
    while(input > 0)
    {
        result = result * 10 + (input % 10); // 2
        input /= 10;
    }
    return result;
}
1. Using a plain int instead of its unsigned cousin is sloppy. What if the user passes a negative number? He gets back a zero! Maybe this behavior makes sense, maybe not.
2. A problem I recently solved (Alien numbers) required a similar approach. Here I divide the current input variable value by 10, the modulo is the cipher I am interested in, I add it to the current resulting value (not before multiplying it by ten) and so on till I have processed the complete number.

If you are not sure of what it is going on here, you should try to execute the function by hand. It helps a lot.

No comments:

Post a Comment