Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do reverse the order of the digits in a decimal no in C++?
Posted
Updated 10-Dec-09 9:23am
v2

long double ReverseNumber(unsigned long i)
{
  if(i<10) return i;

  int div=1, digits=0;

  while(i/div){
   digits++; div*=10;
  }

  long double result = 0;
  int tmp = digits;

  for(int x=1; x<=digits; x++){
   result += (i%10)*pow((long double)10, (int)--tmp);
   i/=10;
  }
  
  return result;
}

This will work for a whole number. But any possible special cases are intentionally not handled, code not commented, code may not be fully optimised, gotchas intentionally not taken care of. I've left those as exercises for you to figure out.

If you need to support a number with decimal places, you'll have even more work to do. Ask a more specific question here if needed, with relevant code, showing us what you've tried.
 
Share this answer
 
v8
unsigned long  ReverseLong(unsigned long u)
{
  long n = 0;
  long r;
  while ( u )
  {
    r = u % 10;
    u /= 10;
    n *= 10;
    n += r;
  }
  return n;
}
 
Share this answer
 
v2
unsigned __int64 ReverseNum(unsigned __int64 i)
{
  unsigned __int64 res = 0;

  for( ; i>0; res += i%10, i /= 10)
     res *= 10;

  return res;
}


Basically almost the same as Carlo's (5 for him), but slightly disguised to wrap it in 2 lines. And I'm using only one variable on the stack instead of two. :)
 
Share this answer
 
v4
Serialize it to a string, reverse the string, then parse the string into a decimal number. If that's what you mean.
 
Share this answer
 
v2
Seperate every digit from a number
Take modulus operator to seperate and push to the stack
and pop from the stack.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900