数据结构—大数加法
实现两个整型数据的相加,每个整型数据的长度不超过100位。
考点:注意整型数据的溢出问题
思路:利用栈先入后出的特点来实现从低位到高位的相加。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60#智能实现两个非负整数的大数相加 string add(string a,string b){ stack<char>st1; stack<char>st2; stack<char>st3; int asize = a.size(); int asize = b.size(); for(int i=0;i<asize;i++){ //字符串进栈 st1.push(a[i]); } for(int i=0;i<bsize;i++){ st2.push(b[i]); } int flag =0 ;//是否进位标志 while(!st1.empty() && !st2.empty()){ //整数开始相加 int temp = (st1.top()-'0')+(st2.top()-'0')+flag; if(temp>9){ temp = temp%10; flag =1; }else{ flag =0; } st1.pop(); st2.pop(); st3.push(temp+'0'); } while(!st1.empty()){ int temp = st1.top()-'0'+flag; if(temp>9){ temp = temp%10; flag = 1; } else { flag = 0; } st3.push(temp+'0'); st1.pop(); } while(!st2.empty()){ int temp = st2.top()-'0'+flag; if(temp>9){ temp = temp%10; flag = 1; } else { flag = 0; } st3.push(temp+'0'); st2.pop(); } if(flag ==1) st3.push(flag+'0'); string result; while(!st3.empty()){ result += st3.top(); st3.pop(); } return result; }
最后
以上就是朴素板栗最近收集整理的关于数据结构--大数加法的全部内容,更多相关数据结构--大数加法内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复