【保研机试——每日一题】1024 Palindromic Number

【保研机试——每日一题】

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

总结

  1. 字符串反转: reverse(s.begin(),s.end());
  2. 字符串实现大数相加,巧用进位
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值