gpt4 book ai didi

c++ - 添加反转数字

转载 作者:太空宇宙 更新时间:2023-11-04 13:31:31 24 4
gpt4 key购买 nike

我已经编写了 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;
}

最佳答案

#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;
}

关于c++ - 添加反转数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31295136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com