首页 > 代码库 > [leetcode-415-Add Strings]
[leetcode-415-Add Strings]
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- 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.
思路:
模拟手工加法过程,用carry表示进位。
第一个是自己写的,比较啰嗦。
第二个是参考的网上大神的,简洁。
string addStrings(string num1, string num2) { int n1 = num1.length()-1, n2 = num2.length()-1; string ret=""; int digit = 0; int carry = 0; int sum = 0; while (n1 >= 0 && n2 >= 0) { sum = carry + num1[n1--] + num2[n2--] - ‘0‘ - ‘0‘; digit = sum %10; carry = (sum >= 10) ? 1 : 0; ret += (digit+‘0‘); } while (n1 >= 0) { sum = carry + num1[n1--] - ‘0‘; digit = sum % 10; carry = (sum >= 10) ? 1 : 0; ret += (digit + ‘0‘); } while (n2 >= 0) { sum = carry + num2[n2--] - ‘0‘; digit = sum % 10; carry = (sum >= 10) ? 1 : 0; ret += (digit + ‘0‘); } if (carry) ret += ‘1‘; reverse(ret.begin(), ret.end()); return ret; }
string addStrings(string num1, string num2) { int i = num1.size() - 1; int j = num2.size() - 1; int carry = 0; string res = ""; while(i>=0 || j>=0 || carry){ long sum = 0; if(i >= 0){sum += (num1[i] - ‘0‘);i--;} if(j >= 0){sum += (num2[j] - ‘0‘);j--;} sum += carry; carry = sum / 10; sum = sum % 10; res = res + to_string(sum); } reverse(res.begin(), res.end()); return res; }
参考:
https://discuss.leetcode.com/topic/62305/c-_accepted_13ms
[leetcode-415-Add Strings]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。