添加反转数字

时间:2015-07-08 13:14:12

标签: c++

我已经编写了c ++代码来添加反向,输出应该再次与添加的数字相反。你能在我的代码中找到任何错误吗?我试图将它上传到SPOJ.com,它说我的代码错了。谁能帮我吗?  我的代码有点像这样:

int main()
{
    unsigned  long int num1, num2,new_num1=0,new_num2=0,new_num3,final_num=0,quote1,quote2,quote,rem1,rem2,rem3;
    cin>> num1 >> num2;

    quote1=num1;
    quote2=num2;

    while(quote1>0 && quote2>0)
    {
        rem1=quote1%10;
        rem2=quote2%10;


        quote1=quote1/10;
        quote2=quote2/10;


        new_num1=new_num1*10+rem1;
        new_num2=new_num2*10+rem2;
    }
    new_num3=new_num1+new_num2; //add the two reversed numbers
    quote=new_num3;
    while(quote>0)
    {
        rem3=quote%10;
        quote=quote/10;
        final_num=final_num*10+rem3; //reverse the added number
        //cout << final_num << endl;
}
 cout << final_num << endl;
   return 0;
}

1 个答案:

答案 0 :(得分:0)

#include <iostream>
using namespace std;

//Extract the reverse function so you don't have to do it inline
int reverse (int n){
  int ret = 0;
  int r;
  while(n) {
    r = n%10;
    n /= 10;

    ret*=10;
    ret+=r;
  }
  return ret;
}

int main()
{
  unsigned  long int num1, num2, sum;
  cin>> num1 >> num2;
  cerr  << reverse(num1) << " + " << reverse(num2) << endl;
  sum = reverse(num1) + reverse(num2);
  cout << reverse(sum) << endl;
  return 0;
}