在C ++中,如何反转十进制数字中的数字顺序? [英] How do reverse the order of the digits in a decimal no in C++?

查看:226
本文介绍了在C ++中,如何反转十进制数字中的数字顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中反转十进制数字的顺序?

How do reverse the order of the digits in a decimal no in C++?

推荐答案

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.


unsigned long  ReverseLong(unsigned long u)
{
  long n = 0;
  long r;
  while ( u )
  {
    r = u % 10;
    u /= 10;
    n *= 10;
    n += r;
  }
  return n;
}


unsigned __int64 ReverseNum(unsigned __int64 i)
{
  unsigned __int64 res = 0;

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

  return res;
}



基本上与Carlo的相同(对他而言为5),但稍稍变相将其包裹为2行.而且我只在堆栈上使用一个变量,而不是两个. :)



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. :)


这篇关于在C ++中,如何反转十进制数字中的数字顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆