首页 > 代码库 > LeetCode 415 Add Strings
LeetCode 415 Add Strings
Problem:
Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Summary:
以字符串的形式求两个整形数相加。
Analysis:
这道题是一道常规题,并不难,只需一位一位相加,注意在有进位的时候加上进位即可。
1 class Solution { 2 public: 3 string addStrings(string num1, string num2) { 4 int len1 = num1.size(), len2 = num2.size(); 5 int i = len1 - 1, j = len2 - 1, k = 0, carry = 0; 6 char res[5200]; 7 8 while (i >= 0 && j >= 0) { 9 int sum = num1[i] + num2[j] - 2 * ‘0‘ + carry; 10 if (sum > 9) { 11 sum -= 10; 12 carry = 1; 13 } 14 else { 15 carry = 0; 16 } 17 18 res[k++] = sum + ‘0‘; 19 i--; j--; 20 } 21 22 while (i >= 0) { 23 int sum = num1[i] + carry - ‘0‘; 24 if (sum > 9) { 25 sum -= 10; 26 carry = 1; 27 } 28 else { 29 carry = 0; 30 } 31 32 res[k++] = sum + ‘0‘; 33 i--; 34 } 35 36 while (j >= 0) { 37 int sum = num2[j] + carry - ‘0‘; 38 if (sum > 9) { 39 sum -= 10; 40 carry = 1; 41 } 42 else { 43 carry = 0; 44 } 45 46 res[k++] = sum + ‘0‘; 47 j--; 48 } 49 50 if (carry) { 51 res[k++] = ‘1‘; 52 } 53 54 res[k++] = ‘\0‘; 55 56 for (i = 0; i < k / 2; i++) { 57 char tmp = res[i]; 58 res[i] = res[k - i - 2]; 59 res[k - i - 2] = tmp; 60 } 61 62 string resStr = string(res); 63 64 return resStr; 65 } 66 };
以上为我写的原始代码,代码过于冗长,下面是参考网上大牛的代码后优化的代码,代码简介了很多:
1 class Solution { 2 public: 3 string addStrings(string num1, string num2) { 4 int len1 = num1.size(), len2 = num2.size(); 5 int i = len1 - 1, j = len2 - 1, carry = 0; 6 string res = ""; 7 8 while (i >= 0 || j >= 0) { 9 int sum1 = i >= 0 ? num1[i--] - ‘0‘ : 0; 10 int sum2 = j >= 0 ? num2[j--] - ‘0‘ : 0; 11 12 int sum = sum1 + sum2 + carry; 13 res.insert(res.begin(), sum % 10 + ‘0‘); 14 carry = sum / 10; 15 } 16 17 return carry ? "1" + res : res; 18 } 19 };
LeetCode 415 Add Strings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。