题解 | #大数加法#

大数加法

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算两个数之和
     * @param s string字符串 表示第一个整数
     * @param t string字符串 表示第二个整数
     * @return string字符串
     */
    public String solve (String s, String t) {
  StringBuilder builder = new StringBuilder();
        // write code here
        if (s.length() <= 100000 && t.length() <= 100000) {

            if (s.length() == 0) {
                return t;
            }

            if (t.length() == 0) {
                return s;
            }
            if (s.length() < t.length()) {
                String temp = t;
                t = s;
                s = temp;
            }

            System.out.println("t: " + t);
            System.out.println("s: " + s);
            int idx = 0;
            int carry = 0;
            String []res = new String[s.length()];
            Stack<Integer> stack = new Stack<>();
            for (int i = 1; i <= s.length(); i++) {
                //   System.out.println(s.charAt(s.length() - i));
                int ch1 = s.charAt(s.length() - i) - '0';
                //  System.out.println("ch1: " + ch1);
                int ch2 = 0;
                if (i <= t.length()) {
                    ch2 = t.charAt(t.length() - i) - '0';
                }
                //  System.out.println("ch2: " + ch2);


                int sum = ch1 + ch2 + carry;
                //  System.out.println("sum: " + sum);
                carry = sum / 10;
                int zs = sum % 10;
                System.out.println("sum:" + sum + " zs " + zs + " carry " + carry);
                // builder.append(zs);
                // res[i] = zs;
                stack.add(zs);
            }
            //System.out.println(builder.toString());
          
            while (!stack.isEmpty()) {
                builder.append(stack.pop());
            }
            if (carry == 1) {
                return "1" + builder.toString();
            }
        }
        return builder.toString();
    }
}

思路:获取最长的数据作为外层循环,每次获取尾部数据,相加,根据10取模取余,数据放入栈中,因为站先进后出,维持顺序,最后弹出栈,返回

全部评论

相关推荐

不想上班的肱二头肌很...:简历一页,项目突出重点,自我评价可以删掉的
点赞 评论 收藏
分享
未知的命运:大佬这都找不到我还找啥啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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