首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

算法二-大数相乘

2013-11-08 
算法2-大数相乘import java.io.*//数据类封装class IntString {public int lenpublic int[] digitspubl

算法2-大数相乘

import java.io.*;//数据类封装class IntString {public int len;public int[] digits;public IntString() {len = 0;digits = null;}}//算法实现类public class BigInt {public BigInt() {}public static void main(String[] args) throws java.io.IOException {System.out.println("Input two large integers:");IntString intt1 = new IntString();IntString intt2 = new IntString();BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));//通过空格实现字符串分段String str[] = (reader.readLine()).split("\\s+");intt1.digits = convert(str[0]);intt1.len = str[0].length();intt2.digits = convert(str[1]);intt2.len = str[1].length();int[] a = intt1.digits;int[] b = intt2.digits;int alength = intt1.len;int blength = intt2.len;IntString intt3 = new IntString();intt3.len = alength + blength - 1;int clength = intt3.len;int[] c = new int[1000];for (int i = 0; i < alength; i++)for (int j = 0; j < blength; j++)c[i + j] += a[i] * b[j];for (int i = 0; i < c.length; i++) {if (c[i] > 9) {c[i + 1] += c[i] / 10;c[i] = c[i] % 10;}}intt3.digits = c;clength = intt3.len;System.out.println(clength);System.out.println("the result is: ");for (int i = clength - 1; i >= 0; i--) {System.out.print(c[i]);}}//将字符串逆序public static int[] convert(String str) {int length = str.length();int[] tem = new int[length];for (int i = 0; i < str.length(); i++) {tem[i] = str.charAt(length - i - 1) - '0';}return tem;}}

热点排行