The bottom of the BigInteger is implemented with int[].
Before looking at the data structure, always thought that BigInteger is implemented with a linked list. But later found that it was only a practice to increase the difficulty of the use.
It was later found that the string implementation is much faster than the linked list. I thought it was implemented with string.
But a check, only found that the original use int[] to achieve.
Yes, with int[] it saves the trouble of character-to-number!
The addition and multiplication algorithm implemented by string is given below. The idea is the same as our hand.
public string Mulonedigit (string num1, char digit, int. level) {StringBuilder SB = new StringBuilder (); int carry = 0; for (int i = Num1.length ()-1; I >= 0 | | carry! = 0; i--) {int tmp = i < 0? 0:num1.charat (i)-' 0 '; Sb.insert (0, (TMP * (digit-' 0 ') + carry)% 10); carry = (TMP * (digit-' 0 ') + carry)/10; } while (Level > 0) {sb.append (0); level--; } return sb.tostring (); }/** * Use: To circumvent the two loops, and note the highest bit in the case * @param num1 * @param num2 * @return */public string Add (string NUM1, String num2) {StringBuilder sb = new StringBuilder (); int carry = 0; for (int i = Num1.length ()-1, J = num2.length ()-1; I >= 0 | | j>=0 | | Carry! = 0; I--, j--) {int a = i < 0? 0:num1.charat (i)-' 0 '; int B = J < 0? 0:num2.charat (j)-' 0 '; Sb.insert (0, (a+b+carry)% 10); Carry = (A+b+carRY)/10; } return sb.tostring (); public string Multiply (string num1, String num2) {string small, large; if (Num1.length () > Num2.length ()) {large = NUM1; small = num2; }else {large = num2; small = NUM1; } list<string> stringlist = new arraylist<> (); int level = 0; for (int i = Small.length ()-1; I >= 0; i--) {Stringlist.add (Mulonedigit (large, Small.charat (i), level++)); The String result = "0"; for (String str:stringlist) {result = Add (str, result); } if (Result.charat (0) = = ' 0 ') {result = "0"; } return result; }
Java BigInteger Implementation