zoukankan      html  css  js  c++  java
  • Java实现 蓝桥杯 算法提高 p1001

    算法提高 P1001
    时间限制:1.0s 内存限制:256.0MB
    提交此题
      
      当两个比较大的整数相乘时,可能会出现数据溢出的情形。为避免溢出,可以采用字符串的方法来实现两个大数之间的乘法。具体来说,首先以字符串的形式输入两个整数,每个整数的长度不会超过8位,然后把它们相乘的结果存储在另一个字符串当中(长度不会超过16位),最后把这个字符串打印出来。例如,假设用户输入为:62773417和12345678,则输出结果为:774980393241726.

    输入:
      62773417 12345678

    输出:
      774980393241726

    这里作者写了两种方法,既然是Java对大数的处理当然是BigInteger会更加好用了
    import java.math.BigDecimal;
    import java.util.Scanner;
    
    
    public class p1001 { public static void printResult(String A, String B) {
        char[] arrayA = A.toCharArray();
        char[] arrayB = B.toCharArray();
        int len = A.length() + B.length();
        
        int judge = 1;   //用于判定A*B最终结果正负,1代表为正,-1表示为负
        int enda = 0, endb = 0;   //用于指定A和B中最后一个数字的位置(从后往前遍历)
        if(arrayA[0] == '-' && arrayB[0] != '-') {
            judge = -1;
            len = len - 1;
            enda = 1;
        } else if(arrayA[0] != '-' && arrayB[0] == '-') {
            judge = -1;
            len = len - 1;
            endb = 1;
        } else if(arrayA[0] == '-' && arrayB[0] == '-') {
            len = len - 2;
            enda = 1;
            endb = 1;
        }
        
        int[] result = new int[len];
        int a, b;
        for(int i = A.length() - 1, tempi = 0; i >= enda;i--,tempi++) {
            a = arrayA[i] - '0';
            for(int j = B.length() - 1, tempj = 0;j >= endb;j--, tempj++) {
                b = arrayB[j] - '0';    
                result[len-tempi-tempj-2] += (result[len-tempi-tempj-1] + a * b) / 10;  //进位操作    
                result[len-tempi-tempj-1] = (result[len-tempi-tempj-1] + a * b) % 10;  //当前位的数
            }
        }
        int i = 0;
        while(result[i] == 0 && i < len - 1)
            i++;  //除去结果前面的所有多余0,此处使用len-1是因为,若结果全为0,输出最后一个0
        if(judge == -1)
            System.out.print("-");
        for(;i < len;i++)
            System.out.print(result[i]);
    }
    
    public static void biginteger(String a,String b){
    	BigDecimal aa = new BigDecimal(a);
    	BigDecimal bb = new BigDecimal(b);
    	System.out.println(aa.multiply(bb).toString());
    }
    
    
    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        String A = in.next();  //注意,in.next表示遇到空格就不再读入
        String B = in.next();
      //  printResult(A, B);
        biginteger(A,B);
    }
    
    
    }
    
    
  • 相关阅读:
    LVS基于DR模式负载均衡的配置
    Linux源码安装mysql 5.6.12 (cmake编译)
    HOSt ip is not allowed to connect to this MySql server
    zoj 3229 Shoot the Bullet(无源汇上下界最大流)
    hdu 3987 Harry Potter and the Forbidden Forest 求割边最少的最小割
    poj 2391 Ombrophobic Bovines(最大流+floyd+二分)
    URAL 1430 Crime and Punishment
    hdu 2048 神、上帝以及老天爷(错排)
    hdu 3367 Pseudoforest(最大生成树)
    FOJ 1683 纪念SlingShot(矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13079336.html
Copyright © 2011-2022 走看看