Big integer addition

Source: Internet
Author: User

JAVA Implementation

Package classic; import Java. math. biginteger; import Java. util. regEx. matcher; import Java. util. regEx. pattern; public class bigintegeraddition {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub string x = "12314123112313"; string y = "10889129018390813908"; string Z; biginteger A = new biginteger (X ); biginteger B = new biginteger (y); Z =. add (B ). tostring (); system. out. P Rintln (z); system. out. println (add (x, y);} public static int [] tointarray (string Str) {int length = Str. length (); int [] A = new int [length]; for (INT I = 0; I <length; I ++) A [I] = Str. charat (I)-'0'; return a;} public static string add (string a, string B) {if (a = NULL | B = NULL) return NULL; If (! Isnumeric (a) |! Isnumeric (B) return NULL; if (. equals ("0") return B; If (B. equals ("0") return a; if (. length () = B. length () {return addhelp (a, B);} else if (. length ()> B. length () {string x = A; string y = addzerotofirst (B,. length (); Return addhelp (x, y);} else {string y = B; string x = addzerotofirst (A, B. length (); Return addhelp (x, y) ;}} public static string addhelp (string a, string B) {int length =. length (); int [] x = tointarray (a); int [] Y = tointarray (B); int [] Z = new int [Length + 1]; int temp; int diff = 0; For (INT I = length; I> 0; I --) {temp = x [I-1] + Y [I-1] + diff; Z [I] = TEMP % 10; diff = temp/10;} Z [0] = diff; stringbuilder sb = new stringbuilder (); For (INT I = 1-diff; I <= length; I ++) {sb. append (Z [I]);} return sb. tostring ();} public static string addzerotofirst (string STR, int N) {stringbuilder sb = new stringbuilder (); int length = Str. length (); int diff = N-length; while (diff> 0) {sb. append ("0"); diff --;} sb. append (STR); return sb. tostring ();} public static Boolean isnumeric (string Str) {pattern P = pattern. compile ("[0-9] *"); matcher M = P. matcher (STR); Return M. matches ();}}

 

Big integer addition

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.