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.
很简单的一个题目
这是我自己写的一个做法,有点冗余
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public String addStrings(String num1, String num2) { int m = num1.length(); int n = num2.length(); StringBuilder sb = new StringBuilder(); int carry = 0; int i = 0; for (; i < m && i < n; i++) { int b = num1.charAt(m - i - 1) - '0' + num2.charAt(n - i - 1) - '0' + carry; carry = b / 10; sb.insert(0, b % 10); } for (; i < m; i++) { int b = num1.charAt(m - i - 1) - '0' + carry; carry = b / 10; sb.insert(0, b % 10); } for (; i < n; i++) { int b = num2.charAt(n - i - 1) - '0' + carry; carry = b / 10; sb.insert(0, b % 10); } if (carry == 1) sb.insert(0, carry); return sb.toString(); }
|
Discuss里面比较简短的一个
1 2 3 4 5 6 7 8 9 10 11 12 13
| public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0; for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) { int x = i < 0 ? 0 : num1.charAt(i) - '0'; int y = j < 0 ? 0 : num2.charAt(j) - '0'; sb.append((x + y + carry) % 10); carry = (x + y + carry) / 10; } if (carry != 0) sb.append(carry); return sb.reverse().toString(); }
|