我想乘两个字符串,但我得到了错误的答案。任何帮助将AP preciated:
公共类stringmultiplication {
公共静态无效的主要(字串[] args){
字符串S1 =10;
字符串s2 =20;
INT NUM = 0;
的for(int i =(s1.toCharArray()的长度); I> 0;我 - )
对于(INT J =(s2.toCharArray()的长度); J> 0; j--)
NUM =(NUM * 10)+((s1.toCharArray()[I - 1] - '0')*(s2.toCharArray()[J - 1] - '0'));
的System.out.println(NUM);
}
}
解决方案
公共静态无效的主要(字串[] args){
串数字1 =17;
串号码2 =15;
的char [] N1 = number1.toCharArray();
的char [] N2 = number2.toCharArray();
INT结果为0;
的for(int i = 0; I< n1.length;我++){
对于(INT J = 0; J< n2.length; J ++){
结果+ =(n1的[I] - '0')*(N 2 [j]的 - '0')
*(int)的Math.pow(10,n1.length * 2 - (I + J + 2));
}
}
的System.out.println(结果);
}
这应该是正确的执行,而无需使用整数。
I am trying to multiply two strings, but I am getting the wrong answer. Any help will be appreciated:
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 = "17";
String number2 = "15";
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 * 2 - (i + j + 2));
}
}
System.out.println(result);
}
This one should be correct implementation without using integers.
下一篇:在球体上均匀地生成点球体、均匀