1. 題目原址
https://leetcode.com/problems/add-strings/
2. 題目描述
3. 題目大意
給定兩個字元串,将字元串對應位置相加,然後傳回成字元串
4. 解題思路
從後往前周遊。然後使用StringBuilder類型的變量來存儲每一位的相加結果,
5. AC代碼
class Solution {
public String addStrings(String num1, String num2) {
int length1 = num1.length() - 1;
int length2 = num2.length() - 1;
int temp = 0;
StringBuilder sb = new StringBuilder();
while(length1 >= 0 || length2 >= 0 || temp > 0) {
// 從串的後面擷取字元
int a = length1 >= 0 ? num1.charAt(length1 --) - '0':0;
int b = length2 >= 0 ? num2.charAt(length2 --) - '0':0;
// 計算兩個串對應位置的字元相加得到的結果
int yushu = (a + b + temp) % 10;
// 得到相加後的高位數,如果是兩位數12的話,得到的是1
temp = (a + b + temp) / 10;
sb.insert(0,String.valueOf((char)(yushu + '0')));
}
return sb.toString();
}
}
6. 相似題型
【1】989. Add to Array-Form of Integer 解題原址:https://blog.csdn.net/xiaojie_570/article/details/91829848
【2】 66. Plus One 題目原址:https://leetcode.com/problems/plus-one/
【3】 67. Add Binary 題目原址:https://leetcode.com/problems/add-binary/
【4】 415. Add Strings 題目原址:https://leetcode.com/problems/add-strings/