Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most efficient way to reverse a number

I am looking for an efficient algorithm to reverse a number, e.g.

Input: 3456789

Output: 9876543

In C++ there are plenty of options with shifting and bit masks but what would be the most efficient way ?

My platform: x86_64

Numbers range: XXX - XXXXXXXXXX (3 - 9 digits)

EDIT Last digit of my input will never be a zero so there is no leading zeros problem.

like image 540
tommyk Avatar asked Mar 12 '13 06:03

tommyk


2 Answers

Something like this will work:

#include <iostream>

int main()
{
    long in = 3456789;
    long out = 0;
    while(in)
    {
        out *= 10;
        out += in % 10;
        in /= 10;
    }
    std::cout << out << std::endl;
    return 0;
}
like image 67
Stephen Lin Avatar answered Sep 27 '22 23:09

Stephen Lin


#include <stdio.h>
unsigned int reverse(unsigned int val)
{
 unsigned int retval = 0;

 while( val > 0)
 {
     retval  = 10*retval + val%10;
     val     /= 10;
 }
 printf("returning - %d", retval);
 return retval;
}


int main()
{
    reverse(123);
}
like image 37
Murali Medisetty Avatar answered Sep 27 '22 22:09

Murali Medisetty