我是靠谱客的博主 朴素板栗,这篇文章主要介绍数据结构--大数加法,现在分享给大家,希望可以做个参考。

数据结构—大数加法
实现两个整型数据的相加,每个整型数据的长度不超过100位。
考点:注意整型数据的溢出问题
思路:利用栈先入后出的特点来实现从低位到高位的相加。

#智能实现两个非负整数的大数相加
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;
}

最后

以上就是朴素板栗最近收集整理的关于数据结构--大数加法的全部内容,更多相关数据结构--大数加法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(148)

评论列表共有 0 条评论

立即
投稿
返回
顶部