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

高精度整数加法

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)); 
        }
    }
}
全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务