解题思路:
依次从后往前提取每个数,字符型转成int型后,然后进行加法运算
定义两个字符串,用于存储输入的两个
注意事项:
字符串中单个字符的提取
a[0]可能是大于10的数,注意进位问题
temp就是用来给a[0]进位的,数组中存的数是小于10的数
flag是用来在计算的过程中进位的
for循环中的限制应该是长的那个字符串来限制,因为短的用完了,长的可能还会继续进位(如9999和1)
string型转int型可以用强转,也可以直接减去‘0’,我下面的用的是方法2
参考代码:
#include <iostream> using namespace std; int main(int argc, char *argv[]) { string st1,st2,temp0; cin>>st1>>st2; int length1=st1.size(); int length2=st2.size(); if(length1<length2){ temp0=st1; st1=st2; st2=temp0; } int min=(length1<length2)? length1:length2; int max=length1+length2-min; int a[max],flag=0,temp=0; //int max=length1+length2-min; for(int i=max-1;i>=0;i--){ min--; if(min>=0) a[i]=st1[i]-'0'+st2[min]-'0'+flag; else a[i]=st1[i]-'0'+flag; flag=0; temp=a[0]/10;//用于补齐数组的最高位 if(a[i]>9)//用于中间位的进位 { a[i]=a[i]%10; flag=1; } } if(temp!=0) cout<<temp; for(int i=0;i<max;i++) cout<<a[i]; return 0; }
记得点赞哦,欢迎改良和提建议,谢谢
0.0分
1 人评分
c晨光 2018-12-09 20:45:20 |
学你的,都是模仿你的,都是你给的压力我才能进步,你是大佬,