您的位置:首页 > 其它

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 

num1
 and 
num2
 represented as string, return the sum of 
num1
 and 
num2
.

Note:

  1. The length of both 
    num1
     and 
    num2
     is < 5100.
  2. Both 
    num1
     and 
    num2
     contains only digits 
    0-9
    .
  3. Both 
    num1
     and 
    num2
     does not contain any leading zero.
  4. 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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: