大数加减

大数加减(PAT B 1079 延迟的回文数

题目链接:

https://pintia.cn/problemsets/994805260223102976/problems/994805261754023936

思路:

  • 设结构体倒着存储num和num的长度
  • 写一个bign_reverse()返回一个bign的reverse,注意要重新计算长度
  • 写一个判断bign是否回文数的函数,设一个cnt判断循环次数
  • 根据加法法则写一个add函数

代码

#include 
#include 
#include 
using namespace std;
struct bign
{
    int d[10000];
    int len;
    bign() {
        memset(d, 0, sizeof(d));
        len = 0;
    }
};
bign change(string num) {
    bign b;
    b.len = num.size();
    for (int i = 0; i < b.len; i++)
    {
        b.d[b.len - i - 1] = num[i] - '0';
    }
    return b;
}
bool isplid(bign b) {
    int i = 0, j = b.len - 1;
    while (i < j) {
        if (b.d[i] != b.d[j]) {
            return false;
        }
        i++;
        j--;
    }
    return true;
}
bign add(bign b1, bign b2) {
    bign c;
    c.len = 0;
    int carry = 0;
    for (int i = 0; i < b1.len || i < b2.len; i++)
    {
        int temp = b1.d[i] + b2.d[i] + carry;
        c.d[c.len++] = temp % 10;
        carry = temp / 10;
    }
    if (carry != 0) {
        c.d[c.len++] = carry;
    }
    return c;
}
void print(bign b) {
    for (int i = b.len-1; i >=0; i--   )
    {
        printf("%d",b.d[i]);
    }
}
bign bign_reverse(bign b) {
    bign ans;
    for (int i = 0; i < b.len; i++)
    {
        ans.d[i] = b.d[b.len - i - 1];
    }
    int j = b.len - 1;
    while (ans.d[j] == 0) {
        j--;
    }
    ans.len = j + 1;
    return ans;
}
int main()
{
    string num;
    int cnt = 0;
    cin >> num;
    bign b1 = change(num);
  
    while (!isplid(b1)&& cnt++ != 10) {
        print(b1);
        printf(" + ");
        bign b2 = bign_reverse(b1);
        print(b2);
        bign sum = add(b1, b2);
        printf(" = ");
        print(sum);
        printf("\n");
        b1 = sum;
    }
    if (isplid(b1) && cnt < 10) {
        print(b1);
        printf(" is a palindromic number.");
    }
    else {
        printf("Not found in 10 iterations.");
    }
}

你可能感兴趣的:(大数加减)