首页 > 其他 > 详细

[leetcode-415-Add Strings]

时间:2017-07-05 23:35:46      阅读:370      评论:0      收藏:0      [点我收藏+]

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.

思路:

模拟手工加法过程,用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]

原文:http://www.cnblogs.com/hellowooorld/p/7123938.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!