大整数乘法

昨天经历了华为2018笔试的都应该记得这道题吧。

输入两个大整数,输出两数乘积。

在此,先介绍python写法,因为python支持的大整数是无限位数的。

x = input();
y = input();
print(int(x) * int(y))

JAVA常用类库也有一个支持大整数的类:BigInteger

public class Main {
	public static void main(String []args){
		Scanner scanner = new Scanner(System.in);
		BigInteger x = scanner.nextBigInteger();
		BigInteger y = scanner.nextBigInteger();
		System.out.println(x.multiply(y));
	}	
}

那么问题来了,如果你这两种都不知道怎么呢?那就只能用Strign类型按位运算了。

public class Main {
	public static String cal(String num1,String num2){
		int l = num1.length();
		int r = num2.length();
		int [] num = new int[l+r];
		
		for (int i = 0; i < l; i++) {
			int n1 = num1.charAt(l-1-i)-'0';
			int temp = 0;
			for (int j = 0; j < r; j++) {
				int n2 = num2.charAt(r-1-j)-'0';
				temp = temp + num[i+j]+n1*n2;
				num[i+j] = temp % 10;
				temp /= 10;
			}
			num[i+r] = temp;
		}
		
		int i = l+r-1;
		while(i>0 && num[i] == 0){
			i--;
		}
		String res = "";
		while(i >= 0){
			res = res + num[i--];
		}
		return res;
	}
	
	public static void main(String []args){
		Scanner s = new Scanner(System.in);
                String xString = s.nextLine();
                String yString = s.nextLine();
		System.out.println(cal(xString,yString));
	}
}