Long String Number addition

Source: Internet
Author: User

Long string numbers added

Import Java.util.regex.Pattern; /** * @author Clydelou * * */public class Test {/** * @param args/public static string sum (string s, String t) {patter N pattern = pattern.compile ("[0-9]+?"); if (!pattern.matcher (s). Matches () | |!pattern.matcher (t). Matches ()) {System.out.println ("Error"); System.out.println ("s =/" "+s+"/", T =/" "+t+"/""); Return "";} else {StringBuilder sb = new StringBuilder (); int length0 = S.length (); int length1 = T.length (); s = new StringBuilder (s ). Reverse (). toString (); t = new StringBuilder (t). Reverse (). toString (); int min = (Length0 > length1 length1:length0); Boolean flag = (Length0 > length1? true:false); int temp = 0; for (int i = 0; i < min. i++) {char x = S.charat (i); char y = T.charat (i); int result = X-' 0 ' + y-' 0 ' + temp; int R1 = result% 10; temp = RESULT/10; Sb.append (R1); } if (flag) {while (temp!= 0 && min < length0) {int result = S.charat (min)-' 0 ' + temp. int r1 = result% 1 0; temp = RESULT/10; Sb.append (R1); min++; } if (min < length0) {String str = s.substring (min, length0); Sb.append (str);} if (temp!= 0) {sb.append (temp);} else {while (temp!= 0 && min < length1) {int result = T.charat (min)-' 0 ' + temp. int r1 = result% tem p = RESULT/10; Sb.append (R1); min++; } if (min < length1) {String str = t.substring (min, length1); Sb.append (str);} if (temp!= 0) {sb.append (temp);} Return Sb.reverse (). toString (); } public static void Main (string[] args) {//TODO auto-generated method stub String s = "21341234568787667776768685"; s Tring t = "557467674876856785678987464"; String m = "999999999"; String n = "999999999"; System.out.println (sum (S, t)); System.out.println (SUM (t, s)); System.out.println (SUM (m, n)); System.out.println (SUM ("a", "1")); } }

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.