Computer Question (intermediate)-Two super big integers plus and minus (Java)
The Code is as follows:
Public class AddSub {public static void main (String [] args) {String a = "4632864832684683568465765487657665765236465244"; String B = "47"; int [] pa = stringToInts (); int [] pb = stringToInts (B); String ans_add = add (pa, pb); String ans_sub = sub (pb, pa); System. out. println ("the sum result is:" + ans_add); System. out. println ("subtraction Result:" + ans_sub );} /*** convert String type to int array * @ param s * @ return */public static int [] stringToInts (String s) {int [] n = new int [s. length ()]; for (int I = 0; I
= 0 | B _len> = 0) {int temp = 0; if (a_len> = 0 & B _len> = 0) {temp = a [a_len] + B [B _len] + jinwei;} else if (a_len> = 0) {temp = a [a_len] + jinwei ;} else if (B _len> = 0) {temp = B [B _len] + jinwei;} sb. append (temp % 10 + ""); jinwei = temp/10; a_len --; B _len --;} return getNum (sb. reverse ();} public static String sub (int [] a, int [] B) {StringBuffer sb = new StringBuffer (); boolean flag = false; // judge whether a is smaller than B if (. length
= 0 | B _len> = 0) {int temp = 0; if (a_len> = 0 & B _len> = 0) {if (a [a_len]-jiewei)
= 0) {temp = a [a_len]-jiewei; jiewei = 0;} sb. append (temp + ""); a_len --; B _len --;} if (flag) {return getNum (sb. append ("-"). reverse ();} return getNum (sb. reverse ();} // remove the first 0 public static String getNum (StringBuffer sb) {while (sb. length ()> 1 & sb. charAt (0) = '0') {sb. deleteCharAt (0);} return sb. toString ();}}
The running instance is as follows: