求两个大整数相乘的结果不能使用BigInteger和long

    xiaoxiao2021-03-25  153

    提示:

     1、 两个数相乘的值的位数不会超过两者位数之和

     2、char转换成int时,直接用int接受的值为asiic码值, 可以使用Character.getNumericValue(‘3’) 获取实际数值

     3、乘数 * 被乘数    将各位置分别相乘时,要注意索引位置, 最后再计算进数

     4、消除字符串前面的无效字符0, 此处使用正则表达式替换

    代码:

    public static String caculate(String num1,String num2) { int length = num1.length() + num2.length(); //两个数相乘的值不会超过两者位数之和 int[] array = new int[length]; for(int i = num1.length() - 1; i >= 0; i--) { int temp1 = Character.getNumericValue(num1.charAt(i)); if(temp1 == 0) continue; int index =  num1.length() - i -1; // 乘数的位置  个位 0 十位 1 以此类推 for(int j = num2.length()-1; j >= 0; j--) { int temp2 = Character.getNumericValue(num2.charAt(j)); //乘数的某一位与被乘数 各位依次相乘 并且位置index要依次根据乘法运算依次递增 array[index++] += temp1 * temp2;    } } StringBuilder sb = new StringBuilder(); for(int i = 0;i < array.length;i++) { if(array[i] > 10) { int overValue = array[i] / 10; array[i+1] +=  overValue; array[i] %= 10; } sb.insert(0, array[i]); } //去掉字符串前面的0 return sb.toString().replaceAll("^0*", ""); }

    转载请注明原文地址: https://ju.6miu.com/read-13470.html

    最新回复(0)