/**
*超大整數相加:
*題目要求:如果系統要使用超大整數(超過long的范圍),請你設計一個數據結構來存儲這種
*超大型數字以及設計一種算法來實現超大整數的加法運算
*@authorAdministrator
*
*/
publicclass VeryBigNumAdd {
/**
*@paramargs
*/
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
/*
String a="1223232";
for(int i=a.length()-1;i>=0;i--)
{
System.out.print(a.charAt(i));
}
*/
VeryBigNumAdd vbn=new VeryBigNumAdd();
String a="123453243455535634535252345234677576252241234123523453664563634";
String b="123453243455535634535252345234677576252241234123523453664563634";
String result=vbn.doAdd(a,b);
System.out.println("result:"+result);
}
/**
*
*@parama加數字符串1
*@paramb加數字符串2
*@return結果字符串
*分析:
*1、取得兩個字符串的長度
*2、把兩個的長度做比較,并得出較長的長度,及較短的長度
*3、把長度較短的加數字符串,在左面補0,使之與較長的字符串一樣長
*4、從最高位,一個個數的取出來相加,當然首先得轉換為整型
*5、設置進位,如果兩個數相加及加上進位大于等于10,并且這不是最左邊一個字符相加,相加結果等于
* (取出1+取出2+進位)-10,并把進位設為1;如果沒有大于10,就把進位設為0,如些循環,把
* 相加的結果以字符串的形式結合起來,就得到最后的結果
*/
String doAdd(String a,String b)
{
String str="";
int lenA=a.length();
int lenB=b.length();
int maxLen=(lenA>lenB) ? lenA : lenB;
int minLen=(lenA<lenB) ? lenA : lenB;
String strTmp="";
for(int i=maxLen-minLen;i>0;i--)
{
strTmp+="0";
}
//把長度調整到相同
if(maxLen==lenA)
{
b=strTmp+b;
}else
a=strTmp+a;
int JW=0;//進位
for(int i=maxLen-1;i>=0;i--)
{
int tempA=Integer.parseInt(String.valueOf(a.charAt(i)));
int tempB=Integer.parseInt(String.valueOf(b.charAt(i)));
int temp;
if(tempA+tempB+JW>=10 && i!=0)
{
temp=tempA+tempB+JW-10;
JW=1;
}
else
{
temp=tempA+tempB+JW;
JW=0;
}
str=String.valueOf(temp)+str;
}
return str;
}
}