# [LeetCode 415. Add Strings](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3875/) ### Daily challenge Aug 9, 2021 (EASY) >Given two non-negative integers, `num1` and `num2` represented as string, return the sum of num1 and num2 as a string. > >You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. :::info **Example 1:** **Input:** num1 = "11", num2 = "123" **Output:** "134" ::: :::info **Example 2:** **Input:** num1 = "456", num2 = "77" **Output:** "533" ::: :::info **Example 3:** **Input:** num1 = "0", num2 = "0" **Output:** "0" ::: :::warning **Constraints:** * 1 <= num1.length, num2.length <= 104 * num1 and num2 consist of only digits. * num1 and num2 don't have any leading zeros except for the zero itself. ::: --- ### Approach 1 : **`0 ms ( 100% )`** **`O()`** * 讓 `num1` 保持是長度較長的字串,直接對 `num1` 進行運算。 * **`int i = num1.length() - 1`**、**`int j = num2.length() - 1`** 表示兩字串的個位數。 * 直接進行運算 **`sum = num1[i] + num2[j] - 96 + carry`**。 因為 `num2` 長度小於等於 `num1`,所以當 `num2` 遍歷完後還要考慮 `num1` 是否會有進位的問題。 ---> `num1 = "9999"`、`num2 = "1"`。 ```cpp=1 class Solution { public: string addStrings(string num1, string num2) { if(num1.length() < num2.length()) swap(num1, num2); string ans; int i = num1.length() - 1; int j = num2.length() - 1; int carry = 0; while(j >= 0){ int sum = num1[i] + num2[j] - 96 + carry; carry = sum / 10; num1[i] = sum % 10 + 48; i--; j--; } while(i >= 0){ int sum = num1[i] - 48 + carry; carry = sum / 10; num1[i] = sum % 10 + 48; i--; } if(carry == 1) num1.insert(0, "1"); return num1; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up