java大数据相乘_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java大数据相乘

java大数据相乘

 2015/1/23 15:25:07  junfeng279  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.test;publicclassMyMultiply{/***@paramargs*/publicstaticvoidmain(String[]args){//System.out.println("Helloworld");//Stringstr1="1234";//Stringstr2="1234";//Stringstr1="1076060999";//Stringstr2="90188905567"
  • 标签:Java 数据
class="java">package com.test;
public class MyMultiply {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// System.out.println("Hello world");

		//String str1 = "1234";
		//String str2 = "1234";
		//String str1 = "1076060999";
		//String str2 = "90188905567";
		String str1 = "2345678900987766655554444446454564646878768768687867867684684";
		String str2 = "3465874365984375943759438759438753515113546468478674687486748674867468465143513545454613213548787687";

		int len1 = str1.length();
		int len2 = str2.length();

		char[] s1 = str1.toCharArray();
		char[] s2 = str2.toCharArray();

		// 高低位对调
		covertdata(s1, len1);
		covertdata(s2, len2);

		System.out.println("乘数:"+str1);
		System.out.println("乘数:"+str2);
		multiply(s1, len1, s2, len2);

	}

	public static void covertdata(char data[], int len) {
		//高低位对调
		for (int i = 0; i < len / 2; i++) {
			data[i] += data[len - 1 - i];
			data[len - 1 - i] = (char) (data[i] - data[len - 1 - i]);
			data[i] = (char) (data[i] - data[len - 1 - i]);
		}
	}

	public static void multiply(char a[], int alen, char b[], int blen) {
		// 两数乘积位数不会超过乘数位数和+ 3位
		int csize = alen + blen + 3;
		// 开辟乘积数组
		int[] c = new int[csize];
		// 乘积数组填充0
		for (int ii = 0; ii < csize; ii++) {
			c[ii] = 0;
		}
		// 对齐逐位相乘
		for (int j = 0; j < blen; j++) {
			for (int i = 0; i < alen; i++) {
				c[i + j] +=  Integer.parseInt(String.valueOf(a[i]))* Integer.parseInt(String.valueOf(b[j]));
			}
		}
		int m = 0;
		// 进位处理
		for (m = 0; m < csize; m++) {
			int carry = c[m] / 10;
			c[m] = c[m] % 10;
			if (carry > 0)
				c[m + 1] += carry;
		}
		// 找到最高位
		for (m = csize - 1; m >= 0;) {
			if (c[m] > 0)
				break;
			m--;
		}
		// 由最高位开始打印乘积
		System.out.print("乘积:");
		for (int n = 0; n <= m; n++) {
			System.out.print(c[m - n]);
		}
		System.out.println("");
	}
}

?

发表评论
用户名: 匿名