[Leetcode] #415 Add Strings
来源:互联网 发布:灭蚊激光炮淘宝 编辑:程序博客网 时间:2024/06/05 18:31
Discription:
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.
Solution:
string addStrings(string num1, string num2) {if (num1.empty() || num2.empty())return num1.empty() ? num2 : num1;int m = num1.size() - 1, n = num2.size() - 1;string result = "";int carry = 0, temp;while (m >= 0 || n >= 0 || carry){temp = (m >= 0 ? num1[m--] - '0' : 0) + (n >= 0 ? num2[n--] - '0' : 0) + carry;result = char(temp % 10 + '0') + result;carry = temp / 10;}//if (carry > 0)//result = char(carry + '0') + result;return result;}
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;}
0 0
- Leetcode 415 Add Strings
- LeetCode[415] Add Strings
- LeetCode #415: Add Strings
- 【leetcode】415 Add Strings
- Leetcode Add Strings 415
- leetcode-415-Add Strings
- [Leetcode] #415 Add Strings
- leetcode[415]:Add Strings
- LeetCode 415 Add Strings
- Leetcode 415 Add Strings
- LeetCode.415(43) Add Strings&&Multiply Strings
- [LeetCode 415] Add Strings(Python)
- 【LeetCode】415 Add Strings (java实现)
- Sum—LeetCode-415 Add Strings
- Leetcode-415. Add Strings
- LeetCode 415. Add Strings
- [LeetCode]--415. Add Strings
- LeetCode 415. Add Strings
- 手机APP测试之ADB常见问题解决方法
- 5.6(引用和赋值)
- bzoj1974&jzoj1523 [Sdoi2010]auction 代码拍卖会
- SQL Server 查询性能优化——覆盖索引
- 5、spring自动装配之@Qualifier注解的使用
- [Leetcode] #415 Add Strings
- windows安装Pyhon3.6
- idea中web.xml报错 Servlet should have a mapping
- 20170218C++项目班02_01Node实现
- CentOS Apache配置详解
- NOIP 2002
- 设计模式—单一职责原则
- 查询最近三个月的数据
- Amazon Redshift构建新一代数据分析BI系统