The various types of data processed by the computer have a range that cannot be handled beyond the scope.
If you do a large number of operations subtraction, the ordinary method is certainly not, then we encounter large number of operations how to deal with it? Today introduces a method of large number subtraction operation
Ideas:
1. Use a character array as the storage medium for two extra-large integers.
2. A bitwise calculation of the traverse result is ten in one.
3. Flip the array that stores the results.
The following code:
1 Public classLargeintsub {2 Public Static voidMain (string[] args) {3 4String a= "6789";5String b= "123";6 int[]pa=stringtoints (a);7 int[]pb=stringtoints (b);8String result_sub=Sub (PA,PB);9SYSTEM.OUT.PRINTLN ("Sub result is:" +result_sub);Ten } One A Public Static int[] stringtoints (String s) { - int[] n =New int[S.length ()]; - for(inti = 0;i<s.length (); i++){ theN[i] = Integer.parseint (s.substring (i,i+1)); - } - returnN; - } + - Public StaticString Sub (int[]a,int[]b] { +StringBuffer sb=NewStringBuffer (); A Booleanflag=false; at if(a.length<b.length) { - intc[]=A; -a=b;b=C; -flag=true; - } - inta_len= a.length-1; in intB_len=b.length-1; - intDegrade=0; to while(a_len>=0| | B_len>=0){ + intTemp=0; - if(a_len>=0&&b_len>=0){ the if((A[a_len]-degrade) <B[b_len]) { *temp=a[a_len]+10-b[b_len]-degrade; $Degrade=1;Panax Notoginseng}Else{ -temp=a[a_len]-b[b_len]-degrade; the } +}Else if(a_len>=0){ Atemp=a[a_len]-degrade; theDegrade=0; + } -Sb.append (temp+ ""); $ $a_len--;b_len--; - } - if(flag) { the returnGetnum (Sb.append ("-"). reverse ()); - }Wuyi returnGetnum (Sb.reverse ()); the } - Public StaticString getnum (StringBuffer sb) { Wu while(Sb.length () > 1 && sb.charat (0) = = ' 0 ') { -Sb.deletecharat (0); About } $ returnsb.tostring (); - } - -}
Large number plus subtraction-Java implementation