//2.求两个长长整型的数据的和并输出,例如输入1233333333333333。。。 3111111111111111111111111.。。。,则输出。。。。#include<stdio.h> #include <iostream> #include <string> using namespace std; int main() { string num1, num2;//用于保存两个长整数 cin >> num1 >> num2; cout << "num1="<< num1<<",num2="<<num2<<endl; int len1,len2,len; len1 = num1.length(); len2 = num2.length(); len = (len1>=len2)?len1:len2 ; int l = len; int sum_int[len]={0};//用数组保存每位数相加之和 string sum(len+1,‘0‘); //cout << "sum.size=" << sizeof(sum_int)/sizeof(int) << "sum[0]="<< sum_int[0]<<endl;//tes //cout << "sum.size=" << sum.size() << "sum[0]="<< sum[0]<<endl;//test for(len1--,len2--;len1>=0&&len2>=0;len1--,len2--) { sum_int[len]=(num1[len1]-‘0‘) +(num2[len2]-‘0‘); cout << len << "," <<sum_int[len]<<endl; len--; } while(len1>=0) { sum_int[len] = num1[len1]-‘0‘; len--; len1--; } while(len2>=0) { sum_int[len] = num2[len2]-‘0‘; len--; len2--; } for(int j=l;j>=0;j--) { if(sum_int[j]>9) { sum_int[j-1]+=1; sum_int[j]=sum_int[j]%10; } //cout << sum_int[j]<<endl; sum[j] = sum_int[j]+‘0‘; } //跳过开始的0 int k = 0; while(sum[k]==‘0‘) k++; sum = sum.substr(k,l+1); cout << sum << endl; }
解法二://用vector保存每位之和
时间: 2024-10-06 15:43:20