| 1 | public class Solution { |
| 2 | public String addStrings(String num1, String num2) { |
| 3 | StringBuilder sb = new StringBuilder(); |
| 4 | int carry = 0; |
| 5 | // condition is great |
| 6 | // https://leetcode.com/problems/add-strings/discuss/90436/Straightforward-Java-8-main-lines-25ms |
| 7 | for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){ |
| 8 | int x = i < 0 ? 0 : num1.charAt(i) - '0'; |
| 9 | int y = j < 0 ? 0 : num2.charAt(j) - '0'; |
| 10 | sb.append((x + y + carry) % 10); |
| 11 | carry = (x + y + carry) / 10; |
| 12 | } |
| 13 | return sb.reverse().toString(); |
| 14 | } |
| 15 | } |