From Algorithmist
Jump to navigation Jump to search

42 - Adding Reversed Numbers[edit]


This problem requires us to do basic number manipulation, namely reverse two numbers, add them and reverse the sum back. The examples and the problem statement make it somewhat clear on what happens to trailing and leading zeros.


The bulk of the problem is how to reverse a number. To reverse a number, we simply use the modulus operator to obtain the rightmost digit of the original number and then we "add" this to a new number which will eventually become the reverse of the original. For example, given 1998 - we firstly mod the number (by 10) to obtain the number '8' which we then add to our new number which is currently 0, now it becomes 199 (by doing integer division by 10 to get rid of the processed digit) and 8. We again mod the original number to get '9', then we multiply our new number by 10 and add the digit '9', now the numbers are 19 and 89. Just repeat the same process. Adding the two numbers is trivial, just simply use the language's addition operator. Finally to reverse the sum, we simply use the "reversal" method we did earlier.


This simple function does the reversal process as described above.

int rev(int number) {
   int res = 0;
   while (number > 0) {
      res = res * 10 + number%10;
      number /= 10;
   return res;


24 1
4358 754
305 794




See Also[edit]