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

高精度整数加法

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

直接调库

面试官:你觉得自己很幽默?

import java.math.BigInteger;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            BigInteger num1 = new BigInteger(in.next());
            BigInteger num2 = new BigInteger(in.next());
            System.out.println(num1.add(num2));
        }
    }
}

自行模拟

注意最后一位的进位,以及 StringBuilder 的 append 函数是接受直接输入 int 型参数的,它会直接输出字符串形式的数字,类似于 num+"",而不是输出其 ASCII 码对应的字符。

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String num1 = in.next();
            String num2 = in.next();
            StringBuilder sb = new StringBuilder();
            int cin = 0;
            int res = 0;
            for (int i = 0; i < num1.length() || i < num2.length(); i++) {
                int n1 = i < num1.length() ? num1.charAt(num1.length() - 1 - i) - '0' : 0;
                int n2 = i < num2.length() ? num2.charAt(num2.length() - 1 - i) - '0' : 0;
                res = n1 + n2 + cin;
                sb.append(res % 10);
                cin = res / 10;
            }
            if (res >= 10) sb.append('1');
            System.out.println(sb.reverse());
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 11:33
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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