给出1000位的数,判断是否是回文数。10次相加还不是回文数,输出。
stoll(str)
。%s is a palindromic number.
。str[i]=temp
。加法完成后还要再str.resize(len)
一次。#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool is_palindromic(string str) {
string str1 = str;
reverse(str1.begin(), str1.end());
return str1 == str;
}
string add_str(string str1, string str2) { //有可能进位
string ans;
ans.resize(1010);
int carry = 0;
int len = 0;
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
for (int i = 0; i < str1.size(); ++i) {
int temp = str1[i] - '0' + str2[i] - '0' + carry;
char s = temp % 10 + '0';
ans[len++] = s;
carry = temp / 10;
}
if (carry != 0) ans[len++] = carry + '0';
ans.resize(len);
reverse(ans.begin(), ans.end());
return ans;
}
int main() {
string str1, str2, ans;
cin >> str1;
if (is_palindromic(str1)) { //特判
printf("%s is a palindromic number.", str1.c_str());
return 0;
}
for (int i = 0; i < 10; ++i) {
str2 = str1;
reverse(str1.begin(), str1.end());
//ans = to_string(stoll(str1) + stoll(str2)); //stoi可能越界
ans = add_str(str1, str2);
if (is_palindromic(ans)) { //是回文数
printf("%s + %s = %s\n", str2.c_str(), str1.c_str(), ans.c_str());
printf("%s is a palindromic number.\n", ans.c_str());
return 0;
} else { //不是回文数
printf("%s + %s = %s\n", str2.c_str(), str1.c_str(), ans.c_str());
str1 = ans;
}
}
printf("Not found in 10 iterations.");
return 0;
}
本文地址:https://blog.csdn.net/weixin_41945646/article/details/107340990
如对本文有疑问, 点击进行留言回复!!
灰色预测模型GM(1,1)的发展系数a=0或无限接近于0的时候预测的误差以及解决办法
网友评论