leetcode 415. Add Strings

    string addStrings(string num1, string num2) {
        bool carry = false;

        int len1 = num1.size();
        int len2 = num2.size();
        int max_len = len1 >= len2 ? len1 : len2;
        int min_len = len1 < len2 ? len1 : len2;
        string& max_str = len1 >= len2 ? num1 : num2;
        string& min_str = len1 < len2 ? num1 : num2;

        min_len--; max_len--;
        for (; max_len >= 0; min_len--, max_len--) {
            int temp = min_len >= 0 ? min_str[min_len] : '0';
            int ta = max_str[max_len] - '0' + temp - '0' + carry;
            if (ta > 9) {
                carry = true;
                max_str[max_len] = ta - 10 + '0';
            }
            else {
                carry = false;
                max_str[max_len] = ta + '0';
            }
        }
        if (carry)
            return "1" + max_str;
        return max_str;
    }

 

posted on 2018-02-26 11:05  willaty  阅读(113)  评论(0编辑  收藏  举报

导航