栈的应用2——大数相加
发布时间:2020-12-14 02:32:43 所属栏目:大数据 来源:网络整理
导读:public class Example3_2LargeNumAdd {//大数相加/** * 栈的应用实例 * 大数相加 * * * */public String add(String a,String b) throws Exception{LinkStack sum = new LinkStack();LinkStack sA = numSplit(a);LinkStack sB = numSplit(b);int partiaSum;
public class Example3_2LargeNumAdd {
//大数相加
/**
* 栈的应用实例
* 大数相加
*
*
* */
public String add(String a,String b) throws Exception{
LinkStack sum = new LinkStack();
LinkStack sA = numSplit(a);
LinkStack sB = numSplit(b);
int partiaSum; //两个位求和
boolean isCarry = false; //进位标示
while(! sA.isEmpty() && ! sB.isEmpty()){
partiaSum = (Integer)sA.pop() + (Integer)sB.pop();
if(isCarry){
partiaSum++;
isCarry = false;
}
if(partiaSum >= 10){
partiaSum -= 10;
sum.push(partiaSum);
isCarry = true;
}else{
sum.push(partiaSum);
}
}
LinkStack temp = !sA.isEmpty()?sA:sB;
while(!temp.isEmpty()){
if(isCarry){
int t = (Integer)temp.pop();
++t;
if(t >= 19){
t -= 10;
sum.push(t);
}else{
sum.push(t);
isCarry = false;
}
}else{
sum.push(temp.pop());
}
}
if(isCarry){
sum.push(1);
}
String str = new String();
while(!sum.isEmpty()){
str = str.concat(sum.pop().toString());
}
return str;
}
public LinkStack numSplit(String str)throws Exception{
LinkStack s = new LinkStack();
for(int i = 0;i < str.length(); i++){
char c = str.charAt(i);
if( ' ' == c){
continue;
}else if('0' <= c && '9' >= c){
s.push(Integer.valueOf(String.valueOf(c)));
}else{
throw new Exception("非法字符");
}
}
return s;
}
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Example3_2LargeNumAdd e = new Example3_2LargeNumAdd();
System.out.println(e.add("12345612134885","2186416457934345"));
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
