package com.String;
import java.util.ArrayList;
public class SuperLong {
/**
* Description:实现两个超过java所能表示的最大的数的加法
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1="546487932464645979846564654";
String str2="987546549879431316469797949";
SuperLong sl=new SuperLong();
String str=sl.superAdd(str1, str2);
System.out.println(str);
}
public String superAdd(String ad1,String ad2){
char[] list1=ad1.toCharArray();
ArrayList<Integer> reslist=new ArrayList<Integer>();
char[] list2=ad2.toCharArray();
if(ad1.length()>ad2.length()){
int forhead=0;
for(int i=ad2.length()-1;i>-1;i--){
int now=Integer.valueOf(String.valueOf(list2[i]));
int added=Integer.valueOf(String.valueOf(list1[i]));
int res=now+added+forhead;
if(res>=10){
reslist.add(res%10);
forhead=res/10;
}else{
reslist.add(res);
forhead=0;
}
}
if(forhead!=0){
reslist.add(forhead);
}
}else{
int forhead=0;
for(int i=ad1.length()-1;i>-1;i--){
int now=Integer.valueOf(String.valueOf(list1[i]));
int added=Integer.valueOf(String.valueOf(list2[i]));
int res=now+added+forhead;
if(res>=10){
reslist.add(res%10);
forhead=res/10;
}else{
reslist.add(res);
forhead=0;
}
}
if(forhead!=0){
reslist.add(forhead);
}
}
StringBuilder sb=new StringBuilder();
for(Integer i:reslist){
sb.append(i.toString());
System.out.print(i.toString());
}
System.out.println();
return sb.toString();
}
}
|