码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-415-Add Strings]

时间:2017-07-05 23:41:38      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:比较   自己   long   bsp   inpu   present   过程   reverse   ref   

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]

标签:比较   自己   long   bsp   inpu   present   过程   reverse   ref   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!