Archy_ @ 2024-08-20 18:02:15
#include<iostream>
using namespace std;
struct node {
int a[100005], len = 0;
node(int x = 0){
while(x > 0){
a[++ len] = x % 10;
x /= 10;
}
}
void print() {
for(int i = len; i >= 1; i--) {
cout << a[i];
}
}
};
node operator + (const node x, const node y){
node z(0);
z.len = max(x.len, y.len) + 2;
for(int i = 1;i <= z.len; i ++) {
z.a[i] += (x.a[i] + y.a[i]);
if(z.a[i] > 9) {
z.a[i + 1] += (z.a[i] / 10);
z.a[i] %= 10;
}
}
while(z.a[z.len] == 0) z.len--;
return z;
}
int main(){
node a(1), b(2);
a = a + b;
a.print();
a = a + a;
a.print();
return 0;
}
main 函数第一次输出 3,第一次加法没问题,第二次输出了8,就不对了。每次都是第二次加法都不对了。
by yucheng0630 @ 2024-08-20 18:43:24
@hyf719346 壶关
#include <bits/stdc++.h>
#define int long long
const int maxn = 1e5 + 7;
using namespace std;
string a[maxn];
string add(string a, string b)
{
int lena = a.size();
int lenb = b.size();
if (lena < lenb)
{
swap(a, b);
swap(lena, lenb);
}
if (lena > lenb)
{
for (int i = 1; i <= lena - lenb; ++i)
{
b = '0' + b;
}
}
int jinwei = 0;
int num1;
int num2;
int num3;
string ans = "";
num3 = max(lena, lenb);
int sum = 0;
for (int i = num3 - 1; i >= 0; i--)
{
num1 = a[i] - '0';
num2 = b[i] - '0';
sum = num1 + num2 + jinwei;
ans = char(sum % 10 + '0') + ans;
jinwei = sum / 10;
}
if (jinwei != 0)
{
ans = '1' + ans;
}
return ans;
}
signed main()
{
int n;
cin >> n;
a[1] = '1';
a[2] = '2';
for (int i = 3; i <= 5005; ++i)
{
a[i] = add(a[i - 1], a[i - 2]);
}
cout << a[n];
return 0;
}
by Archy_ @ 2024-08-21 10:55:35
@yucheng0630 额,谢谢你了,但是问题已经解决了,a数组没有初始化。