超长数字相乘/大数相乘(java)
超长正整数相加
http://www.nowcoder.com/questionTerminal/5821836e0ec140c1aa29510fd05f45fc
不难但是第一次见的话写起来很麻烦
作业帮图像算法一面原题(白板)
import java.util.Scanner; class test{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while (in.hasNext()){ String s1 = in.nextLine(); String s2 = in.nextLine(); String res = ""; for (int i = s1.length()-1; i >= 0; i--){ String cur = mult(s2, s1.charAt(i)); int k = s1.length() - 1 - i; while (k > 0){ cur += "0"; k--; } res = add(res, cur); } System.out.println(res); } } private static String add(String s1, String s2){ StringBuilder sb = new StringBuilder(); if (s1.length() < s2.length()){ int k = s2.length() - s1.length(); while (k > 0){ s1 = "0" + s1; k--; } }else{ int k = s1.length() - s2.length(); while (k > 0){ s2 = "0" + s2; k--; } } int jw = 0; for (int i = s1.length()-1; i >= 0; i--){ int cur = (int)(s1.charAt(i) + s2.charAt(i) + jw - '0' - '0'); jw = cur / 10; cur %= 10; sb.append(cur); } if (jw == 1) sb.append(1); return sb.reverse().toString(); } private static String mult(String s1, char s2){ StringBuilder sb = new StringBuilder(); int jw = 0; for (int i = s1.length()-1; i >= 0; i--){ int cur = (int)(s1.charAt(i) - '0') * (int)(s2 - '0') + jw; jw = cur / 10; cur = cur % 10; sb.append(cur); } if (jw != 0) sb.append(jw); return sb.reverse().toString(); } }