力扣题-1.2
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:415. 字符串相加
解题思想:从后往前遍历两个字符串,然后进行相加即可
class Solution(object):def addStrings(self, num1, num2):""":type num1: str:type num2: str:rtype: str"""i = len(num1)-1j = len(num2)-1flag = 0result = ""while i >= 0 and j >= 0:if int(num1[i]) + int(num2[j]) + flag >=10:temp = str(int(num1[i]) + int(num2[j]) + flag - 10)result = temp + result flag = 1else:temp = str(int(num1[i]) + int(num2[j]) + flag)result = temp + result flag = 0i = i - 1j = j - 1while i >= 0:if int(num1[i]) + flag >=10:temp = str(int(num1[i]) + flag - 10)result = temp + result flag = 1else:temp = str(int(num1[i]) + flag)result = temp + result flag = 0i = i - 1while j >= 0:if int(num2[j]) + flag >=10:temp = str(int(num2[j]) + flag - 10)result = temp + result flag = 1else:temp = str(int(num2[j]) + flag)result = temp + result flag = 0j = j - 1if flag == 1:result = '1' + result return result
class Solution {
public:string addStrings(string num1, string num2) {
int i = num1.length() - 1;int j = num2.length() - 1;int flag = 0;string result = "";while (i >= 0 && j >= 0) {int sum = (num1[i] - '0') + (num2[j] - '0') + flag;result = to_string(sum % 10) + result;flag = sum / 10;i--;j--;}while (i >= 0) {int sum = (num1[i] - '0') + flag;result = to_string(sum % 10) + result;flag = sum / 10;i--;}while (j >= 0) {int sum = (num2[j] - '0') + flag;result = to_string(sum % 10) + result;flag = sum / 10;j--;}if (flag > 0) {result = to_string(flag) + result;}return result;}
};