Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/add-strings/
- /**
- * Time Complexity: O(max(M, N))
- *
- * Space Complexity: O(max(M, N))
- *
- * M = Length of num1 string. N = Length of num2 string.
- */
- class Solution {
- public String addStrings(String num1, String num2) {
- if (num1 == null || num2 == null) {
- return "";
- }
- if (num1.length() == 0) {
- return num2;
- }
- if (num2.length() == 0) {
- return num1;
- }
- StringBuilder sb = new StringBuilder();
- int i = num1.length() - 1;
- int j = num2.length() - 1;
- int carry = 0;
- while (i >= 0 || j >= 0 || carry > 0) {
- int x = i < 0 ? 0 : num1.charAt(i) - '0';
- int y = j < 0 ? 0 : num2.charAt(j) - '0';
- int sum = x + y + carry;
- sb.append(sum % 10);
- carry = sum / 10;
- i--;
- j--;
- }
- return sb.reverse().toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement