华为面试题目大整数乘法java代码

华为面试题目大整数乘法java代码

package cn.sunline.test;


/**
 * @author huangzhongj
 *
 */
public class BigInt3 {
	public static String multiply(String s1, String s2) {
		int iLengthBefore = s1.length();
		if (s1.length() % 2 != 0) {
			s1 = "0" + s1;
			s2 = "0" + s2;
		}
		if (s1.length() <= 4) {
			int i1 = Integer.valueOf(s1);
			int i2 = Integer.valueOf(s2);
			return i1 * i2 + "";
		}
		String sOneLeft = s1.substring(0, s1.length() / 2);
		String sOneRight = s1.substring(s1.length() / 2);
		String sTwoLeft = s2.substring(0, s1.length() / 2);
		String sTwoRight = s2.substring(s1.length() / 2);
		char[] arrCharHalf = new char[s1.length() / 2];
		char[] arrCharTotal = new char[s1.length()];
		for (int i = 0; i < arrCharTotal.length; i++) {
			if (i > arrCharHalf.length - 1) {
				arrCharTotal[i] = '0';
			} else {
				arrCharTotal[i] = '0';
				arrCharHalf[i] = '0';
			}
		}
		String sRight = multiply(sOneRight, sTwoRight);
		String sCenter1 = multiply(sOneLeft, sTwoRight) + String.valueOf(arrCharHalf);
		String sCenter2 = multiply(sOneRight, sTwoLeft) + String.valueOf(arrCharHalf);
		String sLeft = multiply(sOneLeft, sTwoLeft) + String.valueOf(arrCharTotal);
		String[] arrString = { sRight, sCenter1, sCenter2, sLeft };
		char[] cResult = new char[iLengthBefore * 2];
		for (int i = 0; i < cResult.length; i++) {
			cResult[i] = '0';
		}
		for (String s : arrString) {
			for (int i = 0; i < s.length(); i++) {
				calOneWei(cResult, cResult.length - 1 - i, s.charAt(s.length() - 1 - i));
			}
		}
		return moveZeroChar(cResult);
	}

	public static void main(String[] args) {
		String s1 = "1234567891011121314151617181920";
		String s2 = "2019181716151413121110987654321";
		System.out.println(multiply(s1, s2));
	}

	public static void calOneWei(char[] arr, int iPosition, char cSummand) {
		if (cSummand != '0') {
			arr[iPosition] += cSummand;
			if (arr[iPosition] > 105) {
				arr[iPosition] = (char) (arr[iPosition] - 96 - 10 + 48);
				calOneWei(arr, iPosition - 1, '1');
			} else {
				arr[iPosition] = (char) (arr[iPosition] - 96 + 48);
			}
		}
	}

	public static String moveZeroChar(char[] arrChar) {
		int i;
		for (i = 0; i < arrChar.length; i++) {
			if (arrChar[i] != '0') {
				break;
			}
		}
		if (arrChar[0] == '0') {
			char[] arrCharNew = new char[arrChar.length - i];
			for (int j = i; j < arrChar.length; j++) {
				arrCharNew[j - i] = arrChar[j];
			}
			return String.valueOf(arrCharNew);
		}
		return String.valueOf(arrChar);
	}

}
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/hzj9118/article/details/53124458
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞