415. Add Strings
Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class Solution { public String addStrings(String num1, String num2) { StringBuffer res = new StringBuffer(); int i = num1.length()-1; int j = num2.length()-1; int carry = 0; while (i>=0 || j>=0 || carry!=0) { int sum = 0; if (i >= 0) { sum += (int)(num1.charAt(i) - '0'); i--; } if (j >= 0) { sum += (int)(num2.charAt(j) - '0'); j--; } if (carry != 0) { sum += carry; } int digit = sum % 10; carry = sum / 10; res.insert(0, digit); } return res.toString(); } }
carry sum 处理字符串的运算问题, 在转化成数值: (int) (num1.charAt(i) - '0') 转换成数值(同 Character.getNumericValue(char a) ), 非ASCII 码. 再 转化成字符.
也常转化成AScII 码, 在转换成字符串, 所以看看是要数值还是要字符, 还是要数值字符