Interview 150
Add Strings
- Problem
- LC 989
- File
- interview150_LC989AddStrings.java
- Path
- pkg5leetcode/interview150/interview150_LC989AddStrings.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC989AddStrings.java
- Approach
- Add digits from end with carry like grade-school addition.
- Complexity
- Time O(n), Space O(n)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Add Strings | LC 9895 * APPROACH: Add digits from end with carry like grade-school addition.6 * COMPLEXITY: Time O(n), Space O(n)7 */8public class interview150_LC989AddStrings {9 static String addStrings(String num1, String num2) {10 StringBuilder sb = new StringBuilder();11 int i = num1.length() - 1, j = num2.length() - 1, carry = 0;12 while (i >= 0 || j >= 0 || carry > 0) {13 int sum = carry;14 if (i >= 0) sum += num1.charAt(i--) - '0';15 if (j >= 0) sum += num2.charAt(j--) - '0';16 sb.append(sum % 10);17 carry = sum / 10;18 }19 return sb.reverse().toString();20 }21 22 public static void main(String[] args) {23 check(addStrings("11", "123").equals("134"), "case1");24 check(addStrings("456", "77").equals("533"), "case2");25 System.out.println("all tests passed");26 }27 28 static void check(boolean cond, String name) {29 if (!cond) throw new AssertionError("FAILED: " + name);30 System.out.println(" PASS " + name);31 }32}