【leetcode】415. Add Strings

problem

415. Add Strings

solution:

class Solution {
public:
    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)
        {
            int tmp = ((i<0)?0:(num1[i--]-'0')) + ((j<0)?0:(num2[j--]-'0')) + carry;//注意运算符的优先级顺序.
            carry = tmp/10;
            res = to_string(tmp%10) + res;   
        }
        return carry ? ('1'+res) : res;//err.
    }
};

 

 

 

参考

1. Leetcode_415. Add Strings;

posted on 2019-03-04 19:08  鹅要长大  阅读(254)  评论(0编辑  收藏  举报

导航