Use a string to simulate the addition of two large numbers -- java implementation, large numbers java
Problem:
The basic int type cannot be directly used for the addition of large numbers, because the integer that int can represent is limited and cannot meet the requirements of large numbers. You can use a string to represent a large number, simulating the process of adding a large number.
Ideas:
1. Reverse the two strings to facilitate the increase of the number of bits from the low position to the high position and the carry of the highest bit;
2. Alignment two strings, that is, the high position of the short string is supplemented with '0' to facilitate the addition of the following strings;
3. Add two positive integers, one plus and one plus carry.
The Code is as follows:
/*** Use a String to simulate the addition of two large numbers * @ param n1 addition 1 * @ param n2 Addition 2 * @ return addition result */public static String add2 (String n1, String n2) {StringBuffer result = new StringBuffer (); // 1. Reverse string n1 = new StringBuffer (n1 ). reverse (). toString (); n2 = new StringBuffer (n2 ). reverse (). toString (); int len1 = n1.length (); int len2 = n1.length (); int maxLen = len1> len2? Len1: len2; boolean nOverFlow = false; // whether to cross-border int nTakeOver = 0; // overflow quantity // 2. fill two strings, that is, the high position of the short string with 0. if (len1 <len2) {for (int I = len1; I <len2; I ++) {n1 + = "0" ;}} else if (len1> len2) {for (int I = len2; I <len1; I ++) {n2 + = "0" ;}}// 3. add two positive integers, one digit and one digit plus carry for (int I = 0; I <maxLen; I ++) {int nSum = Integer. parseInt (n1.charAt (I) + "") + Integer. parseInt (n2.charAt (I) + ""); if (nSum> = 10) {if (I = (maxLen-1) {nOverFlow = true;} nTakeOver = 1; result. append (nSum-10);} else {nTakeOver = 0; result. append (nSum) ;}}// if overflow occurs, the if (nOverFlow) {result is added. append (nTakeOver);} return result. reverse (). toString ();}
Test:
public static void main(String[] args) { String str = add2("911","222"); System.out.println(str); }
Result:
1133
Thank you!