我正在尝试将两个字符串相乘,但我得到了错误的答案。任何帮助将不胜感激:
public class stringmultiplication {
public static void main(String[] args) {
String s1 = "10";
String s2 = "20";
int num = 0;
for(int i = (s1.toCharArray().length); i > 0; i--)
for(int j = (s2.toCharArray().length); j > 0; j--)
num = (num * 10) + ((s1.toCharArray()[i - 1] - '0') * (s2.toCharArray()[j - 1] - '0'));
System.out.println(num);
}
}
最佳答案
public static void main(String[] args) {
String number1 = "108";
String number2 = "84";
char[] n1 = number1.toCharArray();
char[] n2 = number2.toCharArray();
int result = 0;
for (int i = 0; i < n1.length; i++) {
for (int j = 0; j < n2.length; j++) {
result += (n1[i] - '0') * (n2[j] - '0')
* (int) Math.pow(10, n1.length + n2.length - (i + j + 2));
}
}
System.out.println(result);
}
这应该是不使用整数的正确实现。
关于java - 字符串乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446326/