這個只能夠用字符串的形式來處理了,因為計算機能夠處理的最大是long型,本文以字符串的形式來進行超大數(shù)據(jù)的相加,理論上只要你的內(nèi)存允許,相加多大的數(shù)都可以。
/**
*超大整數(shù)相加:
*題目要求:如果系統(tǒng)要使用超大整數(shù)(超過long的范圍),請你設(shè)計一個數(shù)據(jù)結(jié)構(gòu)來存儲這種
*超大型數(shù)字以及設(shè)計一種算法來實現(xiàn)超大整數(shù)的加法運算
*@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加數(shù)字符串1
*@paramb加數(shù)字符串2
*@return結(jié)果字符串
*分析:
*1、取得兩個字符串的長度
*2、把兩個的長度做比較,并得出較長的長度,及較短的長度
*3、把長度較短的加數(shù)字符串,在左面補0,使之與較長的字符串一樣長
*4、從最高位,一個個數(shù)的取出來相加,當然首先得轉(zhuǎn)換為整型
*5、設(shè)置進位,如果兩個數(shù)相加及加上進位大于等于10,并且這不是最左邊一個字符相加,相加結(jié)果等于
* (取出1+取出2+進位)-10,并把進位設(shè)為1;如果沒有大于10,就把進位設(shè)為0,如些循環(huán),把
* 相加的結(jié)果以字符串的形式結(jié)合起來,就得到最后的結(jié)果
*/
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";
}
//把長度調(diào)整到相同
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;
}
}
posted on 2009-08-15 15:58
末日風情 閱讀(1063)
評論(0) 編輯 收藏 所屬分類:
java編程