Multiply Strings

本文介绍了一种处理任意精度大数乘法的方法,通过将字符串形式的大整数转换为整型数组,再利用传统的乘法算法进行计算,并将结果转换回字符串形式返回。这种方法适用于超出常规整型变量表示范围的极大数值。

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

public class Solution {
	public static void main(String[] args) {
		System.out.println(multiply("0", "0"));
	}
	
    public static String multiply(String num1, String num2) {
        if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return "";
        int[] number1 = toIntegerArray(num1);
        int[] number2 = toIntegerArray(num2);
        int[] result = new int[num1.length() + num2.length()];
        
        int startIndex = 0;
        for (int i = num1.length() - 1; i >= 0; i--) {
            int extra = 0;
            for (int j = num2.length() - 1; j >= 0; j--) {
                int value = number1[i] * number2[j] + result[(result.length - 1) - startIndex + j - (num2.length() - 1)] + extra;
                extra = value / 10;
                value = value % 10;
                result[(result.length - 1) - startIndex + j - (num2.length() - 1)] = value;                
            }
            result[(result.length - 1) - startIndex -1 - (num2.length() - 1)] = extra;
            startIndex++;
        }
        String str = "";
        boolean isBeginningZero = true;
        for (int i = 0; i < result.length; i++) {
        	if (result[i] == 0 && isBeginningZero == true) {
        		
        	} else {
        		isBeginningZero = false;
        		str += result[i];
        	}
        }
        return str == "" ? "0" : str;
    }
    
    public static int[] toIntegerArray(String num) {
        if (num == null || num.length() == 0) return null;
        int length = num.length();
        int[] arr = new int[length];
        for (int i = 0; i < length; i++) {
            arr[i] = num.charAt(i) - '0';
        }
        return arr;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值