51nod 1027 大数乘法
2016-09-12 21:58
429 查看
给出2个大整数A,B,计算A*B的结果。
Input
Output
Input示例
Output示例
第二种解法:利用把大数以字符串的形式输入,变成字符
放在字符数组中,因为此时最高位在数组第一位,最低位
在数组最后一位,为了便于计算,将数组中对应高低位调
换,再定义乘积结果的整型数组,先将乘积结果数组的各
个位置置0,再把字符数组中的字符变成整数一位位的相乘,
在计算的过程中注意每一位要加上之前的值,然后计算进
位和每一位的数,最后输出结果
Input
第1行:大数A 第2行:大数B (A,B的长度 <= 1000,A,B >= 0)
Output
输出A * B
Input示例
123456 234567
Output示例
28958703552
import java.math.BigInteger; import java.util.Scanner; public class answer { public static void main(String[] args) { Scanner cin=new Scanner(System.in); String str1=cin.nextLine(); String str2=cin.nextLine(); BigInteger m=new BigInteger(str1); BigInteger n=new BigInteger(str2); BigInteger ans=m.multiply(n); System.out.println(ans); } }
第二种解法:利用把大数以字符串的形式输入,变成字符
放在字符数组中,因为此时最高位在数组第一位,最低位
在数组最后一位,为了便于计算,将数组中对应高低位调
换,再定义乘积结果的整型数组,先将乘积结果数组的各
个位置置0,再把字符数组中的字符变成整数一位位的相乘,
在计算的过程中注意每一位要加上之前的值,然后计算进
位和每一位的数,最后输出结果
import java.math.BigInteger; import java.util.Scanner; public class answer { public static void main(String[] args) { Scanner cin=new Scanner(System.in); String str1=cin.nextLine(); String str2=cin.nextLine(); int len1 = str1.length(); int len2 = str2.length(); char[] s1 = str1.toCharArray(); char[] s2 = str2.toCharArray(); // 高低位对调 covertdata(s1, len1); covertdata(s2, len2); 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--; } // 由最高位开始打印乘积 for (int n = 0; n <= m; n++) { System.out.print(c[m - n]); } } }
相关文章推荐
- 51Nod - 1027 大数乘法
- 51Nod-1027 大数乘法
- 51nod 1027 大数乘法
- 51NOD 1027 大数乘法
- 【51nod】1027 大数乘法
- 51nod -1027 . 大数乘法
- 【51nod】1027 大数乘法
- 51nod 1027 大数乘法
- 1027 大数乘法 ——51Nod
- 51Nod 1027 大数乘法
- 51nod 1027 大数乘法
- 51nod 1027 大数乘法
- 51nod_1027 大数乘法
- 51Nod 1027 大数乘法
- 51Nod-1027-大数乘法
- 51Nod 1027 大数乘法
- 51nod 1027 大数乘法
- 51Nod 1027 大数乘法
- I - 大数乘法 51Nod - 1027
- 51nod 大数乘法