题解 | #高精度整数加法#

高精度整数加法

https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.nextLine();
        String b = in.nextLine();
        LinkedList<Integer> stack1 = new LinkedList<Integer>() {{
            for (char c : a.toCharArray()) {
                push(c - '0');
            }
        }};
        LinkedList<Integer> stack2 = new LinkedList<Integer>() {{
            for (char c : b.toCharArray()) {
                push(c - '0');
            }
        }};
        LinkedList<Integer> stack3 = new LinkedList<>();
        int carry = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty()) {
            int x1 = !stack1.isEmpty() ? stack1.pop() : 0;
            int x2 = !stack2.isEmpty() ? stack2.pop() : 0;
            int sum = x1 + x2 + carry;
            carry = sum >= 10 ? 1 : 0;
            stack3.push(sum >= 10 ? sum - 10 : sum);
        }
        if (carry == 1) {
            stack3.push(1);
        }
        stack3.forEach(System.out::print);
    }
}


#华为笔试#
全部评论

相关推荐

勇敢的90后想交流:我愿意付费上班,楼主你就安心字节待着吧,我是真的喜欢上班
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 11:13
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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