實現兩個大數相乘
阿新 • • 發佈:2018-03-22
stringbu pos 代碼 HR main length top new oid
牛客網鏈接-大數相乘
思路:
- 內心知道這種方法是可以通過的,但是賊雞兒麻煩。
- 輸入兩個字符串。按照筆算乘法的方式,循環計算。考慮到進位的問題。
代碼:
package top.simuhunluo; import java.util.Scanner; public class Main { static StringBuffer[] results; static boolean z = true; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String a = scanner.next(); String b = scanner.next(); int a_len = a.length(); int b_len = b.length(); StringBuffer str_a = new StringBuffer(a); StringBuffer str_b = new StringBuffer(b); results = new StringBuffer[b_len]; for (int i = b_len - 1, k = 0; i >= 0; i--, k++) { results[k] = new StringBuffer(a_len + b_len); int digit_b = str_b.charAt(i) - '0'; int jinwei = 0; int yushu = 0; for (int j = a_len - 1; j >= 0; j--) { int digit_a = str_a.charAt(j) - '0'; int temp = digit_a * digit_b + jinwei; jinwei = temp / 10; yushu = temp % 10; results[k].append(yushu); } results[k].append(jinwei); } for (int i = 0; i < results.length; i++) { for (int j = 0; j < i; j++) { results[i].insert(0, '0'); } for (int j = 0; j < results.length - 1 - i; j++) { results[i].append('0'); } } System.out.println(add(results)); } public static StringBuffer add(StringBuffer[] results) { StringBuffer stringBuffer = new StringBuffer(); int nums = results.length;//加數的個數 int jinwei = 0; for (int i = 0; i < results[0].length(); i++) { int tmp = 0; for (int j = 0; j < nums; j++) { tmp = tmp + results[j].charAt(i) - '0'; } tmp += jinwei; jinwei = tmp / 10; int yushu = tmp % 10; stringBuffer.append(yushu); } stringBuffer.append(jinwei); stringBuffer = stringBuffer.reverse(); while (stringBuffer.charAt(0) == '0') stringBuffer.deleteCharAt(0); return stringBuffer; } }
實現兩個大數相乘