?LeetCode刷題實(shí)戰(zhàn)415:字符串相加
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.
示例
示例 1:
輸入:num1 = "11", num2 = "123"
輸出:"134"
示例 2:
輸入:num1 = "456", num2 = "77"
輸出:"533"
示例 3:
輸入:num1 = "0", num2 = "0"
輸出:"0"
解題
class?Solution?{
public:
????string?addStrings(string?num1, string?num2)?{
????????int?i=num1.size()-1,j=num2.size()-1,carry=0;
????????string?ans;
????????while(i>=0&&j>=0){
????????????carry+=(num1[i]-'0')+(num2[j]-'0'); //從兩個(gè)字符串的后面開始相加,記得加上進(jìn)位
????????????ans.push_back(carry%10+'0'); //將本位的求和結(jié)果放到結(jié)果中
????????????carry/=10;
????????????--i;--j;
????????}
????????while(i>=0){ //和下面的while,這兩個(gè)只會(huì)執(zhí)行其中的一個(gè)
????????????carry+=(num1[i]-'0');
????????????ans.push_back(carry%10+'0');
????????????carry/=10;
????????????--i;
????????}
????????while(j>=0){
????????????carry+=(num2[j]-'0');
????????????ans.push_back(carry%10+'0');
????????????carry/=10;
????????????--j;
????????}
????????while(carry!=0){ //最后記得處理可能不為0的carry
????????????ans.push_back(carry%10+'0');
????????????carry/=10;
????????}
????????reverse(ans.begin(),ans.end()); //將結(jié)果字符串進(jìn)行翻轉(zhuǎn)
????????return?ans;
????}
};
LeetCode1-400題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)401:二進(jìn)制手表
LeetCode刷題實(shí)戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實(shí)戰(zhàn)403:青蛙過河
LeetCode刷題實(shí)戰(zhàn)404:左葉子之和
LeetCode刷題實(shí)戰(zhàn)405:數(shù)字轉(zhuǎn)換為十六進(jìn)制數(shù)
LeetCode刷題實(shí)戰(zhàn)406:根據(jù)身高重建隊(duì)列
LeetCode刷題實(shí)戰(zhàn)407:接雨水 II
LeetCode刷題實(shí)戰(zhàn)408:有效單詞縮寫
LeetCode刷題實(shí)戰(zhàn)409:最長(zhǎng)回文串
LeetCode刷題實(shí)戰(zhàn)410:分割數(shù)組的最大值
LeetCode刷題實(shí)戰(zhàn)411:最短獨(dú)占單詞縮寫
LeetCode刷題實(shí)戰(zhàn)412:Fizz Buzz
LeetCode刷題實(shí)戰(zhàn)413:等差數(shù)列劃分
LeetCode刷題實(shí)戰(zhàn)414:第三大的數(shù)
