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

高精度整数加法

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

  • 遍历自主计算
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @description: TODO
 * @author: Lambert
 * @date: 2022/4/10 16:47
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String s1 = bufferedReader.readLine();
        String s2 = bufferedReader.readLine();
        // result
        StringBuilder stringBuilder = new StringBuilder();
        // 判断哪一个数字更长
        boolean flag = s1.length() < s2.length();
        // 单独保存进位
        int plus = 0;
        /**
         * 遍历运算共有的位数
         */
        for (int i = 0; i < (flag ? s1.length() : s2.length()); i++) {
//            int c1 = Integer.parseInt(s1.substring(s1.length() - i - 1, s1.length() - i));
//            int c2 = Integer.parseInt(s2.substring(s2.length() - i - 1, s2.length() - i));
            int sum = Integer.parseInt(s1.substring(s1.length() - i - 1, s1.length() - i)) + Integer.parseInt(s2.substring(s2.length() - i - 1, s2.length() - i)) + plus;
            stringBuilder.insert(0, sum % 10);
            plus = sum / 10;
        }
        /**
         * 单独添加独有的位数
         */
        if (flag) {
            for (int i = s1.length(); i < s2.length() ; i++) {
//                int c1 = Integer.parseInt(s2.substring(s2.length() - i - 1, s2.length() - i));
                int sum = Integer.parseInt(s2.substring(s2.length() - i - 1, s2.length() - i)) + plus;
                stringBuilder.insert(0, sum % 10);
                plus = sum / 10;
            }
        } else {
            for (int i = s2.length(); i < s1.length() ; i++) {
//                int c1 = Integer.parseInt(s1.substring(s1.length() - i - 1, s1.length() - i));
                int sum = Integer.parseInt(s1.substring(s1.length() - i - 1, s1.length() - i)) + plus;
                stringBuilder.insert(0, sum % 10);
                plus = sum / 10;
            }
        }
        // 若仍有进位,则添加
        if (plus!=0) stringBuilder.insert(0, plus);
        System.out.println(stringBuilder.toString());
    }
    
}

  • 大整数运算
import java.util.Scanner;
import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String s1 = scan.next();
            String s2 = scan.next(); 
            BigInteger a = new BigInteger(s1); 
            BigInteger b = new BigInteger(s2);
            System.out.println(a.add(b)); 
        }
    }
}
全部评论

相关推荐

11-29 11:21
门头沟学院 Java
总包48.5w,意想不到的价格
无情咸鱼王的秋招日记之薛定谔的Offer:R
点赞 评论 收藏
分享
10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-27 10:48
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务