LeetCode415 - Add Strings 用字符串模拟整数相加
2017-04-09 21:51
169 查看
原文链接:http://www.cnblogs.com/vincent93/p/6686627.html
415. Add Strings
Given two non-negative integers
num1and
num2represented as string, return the sum of
num1and
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.
思路:控制num1的长度不小于num2的长度,在num1上直接做修改。
class Solution { public: string addStrings(string num1, string num2) { int len1 = num1.size(), len2 = num2.size(); if (len2 > len1) { swap(len1, len2); swap(num1, num2); } int i = len1 - 1, j = len2 - 1; int carry = 0, a = 0, b = 0, sum = 0; while (i >= 0) { a = num1[i] - '0'; if (j >= 0) b = num2[j] - '0'; else b = 0; sum = a + b + carry; if (sum >= 10) { sum -= 10; carry = 1; } else carry = 0; num1[i] = sum + '0'; --i;--j; } if (carry == 1) num1 = '1' + num1; return num1; } };
转载于:https://www.cnblogs.com/vincent93/p/6686627.html
相关文章推荐
- leetcode_415(两个数字字符串相加,模拟大数相加)
- 做题笔记-LeetCode415字符串相加
- [LeetCode] Add Strings 字符串相加
- 每天一道LeetCode-----将用数组表示的整数加一,两个用字符串表示的(二进制)数相加
- LeetCode425——Add Strings(两个字符串中的数字相加(十进制或二进制),输出字符串形式的结果)
- leetcode415---字符串大数相加
- leetcode-字符串转整数(atoi)
- 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】
- 将两整数数字字符串相加将结果输出
- LeetCode 8.字符串转换整数
- 415. 字符串相加
- LeetCode 8. String to Integer (atoi)(字符串转整数)
- 基础算法之字符串转整数(Leetcode-8)
- LeetCode第八题 字符串转换整数(atoi)(java)
- 415. 字符串相加
- Datawhale-LeetCode集训打卡-字符串转换整数 (atoi)
- LeetCode: 字符串转换到整数
- 两个大数相加,使用字符串模拟相加过程
- Leetcode 415 Add Strings
- leetcode -- 445. Add Two Numbers II 【栈 + 正整数相加】