面试中遇到的笔试题目,手写两个大数相乘,不能用BigInteger (Java)
/** * @Title: Test * @ProjectName client * @date 2019/11/1413:53 */ public class Test { public static void main(String[] args) { String multiply1 = multiply("200", "200"); System.out.println(multiply1); } /** * 01234 数组索引 * 400 第一次循环 * 000 第二次循环 * 000 第三次循环 * 公式:AB*CD = AC (BC+ AD) BD * 67*89 = 6*8(7*8 + 6*9)7*9 * 67*89 = 48(110)63 * 63进6剩余3 * 110变成116,满十进位,进行11,剩余6, * 48变成59。所以: 5963 * 参考博客: https://blog.csdn.net/outsanding/article/details/79472376 * @param num1 * @param num2 * @return */ public static String multiply(String num1, String num2) { int num1_len = num1.length(); int num2_len = num2.length(); int[] numArr = new int[num1_len + num2_len]; for (int i = 0; i < num1_len; i++) { int a = num1.charAt(i) - '0'; for (int j = 0; j < num2_len; j++) { int b = num2.charAt(j) - '0'; numArr[i + j] += a * b; } } // 从个位数向前一位进位 for (int i = numArr.length - 1; i > 0; i--) { numArr[i - 1] += numArr[i] / 10; numArr[i] = numArr[i] % 10; } // 结果拼接 String ret = ""; for (int i = 0; i < numArr.length - 1; i++) { ret += numArr[i]; } return ret; } }