長字串數字相加

來源:互聯網
上載者:User

長字串數字相加

import java.util.regex.Pattern; /** * @author clydelou * */ public class Test { /** * @param args */ public static String sum(String s, String t) { Pattern 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 % 10; 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 % 10; temp = 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"; String 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")); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.