长字符串数字相加

长字符串数字相加

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")); } }

你可能感兴趣的:(String,Class,import)