字符串模拟大数相加——Java实现
本题是CVTE二面编程题,首先考虑返回值肯定是一个字符串(int会有溢出可能),并且两个字符串只含数字,不含”+“、”-“这种。
代码如下:
1 public static String add(String str1, String str2) { 2 if(str1 == null) 3 return str2; 4 if(str2 == null) 5 return str1; 6 StringBuffer s1 = new StringBuffer(str1).reverse(); 7 StringBuffer s2 = new StringBuffer(str2).reverse(); 8 StringBuffer res = new StringBuffer(); 9 int len1 = s1.length(); 10 int len2 = s2.length(); 11 int len; 12 if(len1 < len2) { 13 len = len2; 14 int count = len2 - len1; 15 while(count-- > 0) 16 s1.append('0'); 17 } else { 18 len = len1; 19 int count = len1 - len2; 20 while(count-- > 0) 21 s2.append('0'); 22 } 23 int overflow = 0; 24 int num; 25 for(int i = 0; i < len; i++) { 26 num = s1.charAt(i) - '0' + s2.charAt(i) - '0' + overflow; 27 if(num >= 10) { 28 overflow = 1; 29 num -= 10; 30 } else { 31 overflow = 0; 32 } 33 res.append(String.valueOf(num)); 34 } 35 if(overflow == 1) 36 res.append(1); 37 38 return res.reverse().toString(); 39 }