【保研机试——每日一题】
5.22
题目
代码
朴素版
//朴素版
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
bool isHuiWen(LL n)
{
LL t = n, x = 0;
while (t)
{
x = x * 10 + t % 10;
t /= 10;
}
return n == x;
}
int main()
{
LL n, k;
cin >> n >> k;
int cnt = 0;
while (!isHuiWen(n) && cnt < k)
{
int x = 0, t = n;
while (t)
{
x = x * 10 + t % 10;
t /= 10;
}
n += x;
cnt++;
}
cout << n << endl
<< cnt << endl;
return 0;
}
string实现大数相加
#include <bits/stdc++.h>
using namespace std;
//大数相加 a+b = ans ,addr 表示低位向高位的进位,返回字符串是反的
//字符串反转 reverse(s.begin(),s.end());
string strAdd(string a, string b)
{
string ans = "";
int addr = 0;
for (int i = a.length() - 1; i >= 0; i--)
{
addr = a[i] - '0' + b[i] - '0' + addr;
ans += addr % 10 + '0';
addr /= 10;
}
if (addr != 0)
ans += addr + '0';
return ans;
}
int main()
{
string n;
int k, i;
cin >> n >> k;
string rn;
for (i = 0; i < k; i++)
{
rn = n;
reverse(rn.begin(), rn.end());
if (rn == n)
break;
n = strAdd(n, rn);
}
cout << rn << endl
<< k << endl;
}
总结
- 字符串反转:
reverse(s.begin(),s.end());
- 字符串实现大数相加,巧用进位