题解 | #大数加法#

大数加法

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;
    }
};
全部评论

相关推荐

07-07 14:30
复旦大学 Java
遇到这种人我也不知道说啥了
无能的丈夫:但我觉得这个hr语气没什么问题啊(没有恶意
点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务