Packageadd;ImportJava.math.BigInteger; Public classBigadd { Public Staticstring Bigadd (String n1, string n2) {//string buffers: Improving the efficiency of string manipulationStringBuffer result =NewStringBuffer (); //Invert stringN1 =reverse (N1); N2=reverse (N2); //Maximum length intLen1 =n1.length (); intLen2 =n2.length (); //Maximum length intMaxLen =Max (len1, len2); //If rounding is required Booleanover =false; //the high position of the short string is 0 paddedcover (N1, N2, Len1, len2); for(inti = 0; i < MaxLen; i++) { //add each bit intNSum = Changetoint (n1, i) +Changetoint (n2, i); if(NSum < 9) { //last have carry if(over =true) { if(NSum = = 9) {result.append (0); } Else{result.append (nSum+ 1); //Cancel Roundingover =false; } } Else{result.append (nSum); } } Else { if(Over = =true) {result.append (NSum-10 + 1); } Else{result.append (nSum-10); over=true; } } } //is there a final carry? if(Over = =true) {result.append (1); } returnresult.reverse (). toString (); } Public Staticstring Reverse (string n) {n=NewStringBuffer (n). Reverse (). toString (); returnN; } Public Static intMaxintAintb) {returna > B?a:b; } Public Static intChangetoint (String N,inti) {//add "" to convert character to string returnInteger.parseint (N.charat (i) + ""); } Public Static voidCover (string n1, string n2,intLen1,intlen2) { if(Len1 <len2) { for(inti = len1; i < len2; i++) {N1+ = "0"; } } Else if(Len1 >len2) { for(inti = len2; i < len1; i++) {n2+ = "0"; } } } //Test Public Static voidMain (string[] args) {String N1= "666666666666666666"; String N2= "696969696969696969"; String N=Bigadd (N1, N2); SYSTEM.OUT.PRINTLN (n); //Verify with BigInteger classBigInteger B1 =NewBigInteger (N1); BigInteger B2=NewBigInteger (n2); System.out.println (B1.add (B2)); }}
Do not use the BigInteger class to implement large number additions (Java)