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

高精度整数加法

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        StringBuilder ans = new StringBuilder();

        // 保证a是长串,便于处理
        int n1 = a.length();
        int n2 = b.length();
        if (n1 < n2) {
            String temp = a;
            a = b;
            b = temp;
        }
        int shorter = Math.min(n1, n2);
        int longer = Math.max(n1, n2);
        int sub = longer - shorter;
        // 进位
        int carry = 0;
        for (int i = longer - 1; i - sub >= 0; i--) {
            int x = a.charAt(i) - '0';
            int y = b.charAt(i - sub) - '0';
            if (x + y + carry >= 10) {
                int temp = (x + y + carry) % 10;
                carry = 1;
                ans.insert(0, temp);
            } else {
                int temp = x + y + carry;
                ans.insert(0, temp);
                carry = 0;
            }
        }
        for (int i = longer - shorter - 1; i >= 0; i--) {
            int x = a.charAt(i) - '0';
            if (x + carry >= 10) {
                int temp = (x + carry) % 10;
                ans.insert(0, temp);
                carry = 1;
            } else {
                int temp = x + carry;
                ans.insert(0, temp);
                carry = 0;
            }
        }
        if (carry == 1) {
            ans.insert(0, 1);
        }
        System.out.println(ans);
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务