• 实现两个大数相乘


    牛客网链接-大数相乘

    思路:

    1. 内心知道这种方法是可以通过的,但是贼鸡儿麻烦。
    2. 输入两个字符串。按照笔算乘法的方式,循环计算。考虑到进位的问题。

    代码:

    package top.simuhunluo;
    
    import java.util.Scanner;
    
    public class Main {
        static StringBuffer[] results;
        static boolean z = true;
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String a = scanner.next();
            String b = scanner.next();
            int a_len = a.length();
            int b_len = b.length();
            StringBuffer str_a = new StringBuffer(a);
            StringBuffer str_b = new StringBuffer(b);
            results = new StringBuffer[b_len];
            for (int i = b_len - 1, k = 0; i >= 0; i--, k++) {
                results[k] = new StringBuffer(a_len + b_len);
                int digit_b = str_b.charAt(i) - '0';
                int jinwei = 0;
                int yushu = 0;
                for (int j = a_len - 1; j >= 0; j--) {
                    int digit_a = str_a.charAt(j) - '0';
                    int temp = digit_a * digit_b + jinwei;
                    jinwei = temp / 10;
                    yushu = temp % 10;
                    results[k].append(yushu);
                }
                results[k].append(jinwei);
            }
            for (int i = 0; i < results.length; i++) {
                for (int j = 0; j < i; j++) {
                    results[i].insert(0, '0');
                }
                for (int j = 0; j < results.length - 1 - i; j++) {
                    results[i].append('0');
                }
            }
            System.out.println(add(results));
        }
    
        public static StringBuffer add(StringBuffer[] results) {
            StringBuffer stringBuffer = new StringBuffer();
            int nums = results.length;//加数的个数
            int jinwei = 0;
            for (int i = 0; i < results[0].length(); i++) {
                int tmp = 0;
                for (int j = 0; j < nums; j++) {
                    tmp = tmp + results[j].charAt(i) - '0';
                }
                tmp += jinwei;
                jinwei = tmp / 10;
                int yushu = tmp % 10;
                stringBuffer.append(yushu);
            }
            stringBuffer.append(jinwei);
            stringBuffer = stringBuffer.reverse();
            while (stringBuffer.charAt(0) == '0') stringBuffer.deleteCharAt(0);
            return stringBuffer;
        }
    }
    
  • 相关阅读:
    使用控制台来启动.net core 的程序
    论钱的意义
    js 将图片转换为 base64
    CPU 的由来
    C# Cef winform 脚本的执行 踩过的坑
    什么是JSONP?
    Cookie和Session
    request
    response和ServletContext和乱码问题
    Servilet初步
  • 原文地址:https://www.cnblogs.com/simuhunluo/p/8620756.html
Copyright © 2020-2023  润新知