题解 | #大数加法#

大数加法

http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

使用大数加法的常规解法,模拟笔算加法的过程。从字符串末尾开始相加,将相加的结果入栈。计算完后将栈中元素逐次出栈,并添加到结果字符串末端即可。

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算两个数之和
     * @param s string字符串 表示第一个整数
     * @param t string字符串 表示第二个整数
     * @return string字符串
     */
    string solve(string s, string t) {
        // write code here
        stack<int> re;
        string result;
        int is = s.length()-1;
        int it = t.length()-1;
        int pre = 0;
        while(is >= 0 && it >= 0){
            int n1 = s[is]-'0';
            int n2 = t[it]-'0';
            int n = n1 + n2 + pre;
            pre = 0;
            if(n-10 >= 0){
                pre++;
                n -= 10;
            }
            re.push(n);
            is--;
            it--;
        }
        while(is >= 0){
            int n = s[is]-'0';
            n += pre;
            pre = 0;
            if(n-10 >= 0){
                pre++;
                n -= 10;
            }
            re.push(n);
            is--;
        }
        while(it >= 0){
            int n = t[it]-'0';
            n += pre;
            pre = 0;
            if(n-10 >= 0){
                pre++;
                n -= 10;
            }
            re.push(n);
            it--;
        }
        if(pre == 1){
            re.push(1);
        }
        while(re.size() > 0){
            result += to_string(re.top());
            re.pop();
        }
        return result;
    }
};
全部评论

相关推荐

01-18 09:26
已编辑
门头沟学院 Java
王桑的大offer:建议中间件那块写熟悉即可,写掌握 面试包被拷打到昏厥
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务