编程人员,
数字以尽可能小的整数数组向后存储:
int[] numberA = {7, 3, 6, 2, 1}; //representing number 12,637
int[] numberB = {7, 3, 3}; //representing number 337
现在我想编写一个函数来返回这两个数字的乘积:
static int[ ] times(int[ ]a, int[ ] b) {
//numberA x numberB = product
return product;
}
因为12,637 x 337 = 4,258,669,返回的数组应该如下所示:
product = {9, 6, 6, 8, 5, 2, 4};
所有这一切都应该在不使用Java API的帮助力的情况下工作(例如java.util.ArrayList
)。
我已经在可以使用的相同脚本中创建了类似的函数:
int[] add(int[] int[])
)int[] timesInt(int[], int)
)int[] copy(int[])
)int[] fromInt(int)
)
感谢
答案 0 :(得分:0)
您知道Karatsuba还是Cook算法?也许你可以实现它们? https://en.wikipedia.org/wiki/Karatsuba_algorithm https://en.wikipedia.org/wiki/Toom%E2%80%93Cook_multiplication
答案 1 :(得分:0)
我有这个程序,它会在你的问题中发布你创建的结果,我没有像你指定的那样使用像arraylist这样的任何java API,代码是:
public class Test
{
static int[ ] times(int[ ]a, int[ ] b) {
String astr="",bstr="";
for(int i=a.length-1;i>=0;i--)
{
astr=astr+a[i];//Converts the int array's to string to reverse them without any other than String methods.
}
for(int i=b.length-1;i>=0;i--)
{
bstr=bstr+b[i]; //Converts the int array's to string to reverse them without any other than String methods.
}
int var1=Integer.parseInt(astr); // Converting the reversed string back to int for computing result
int var2=Integer.parseInt(bstr); // Converting the reversed string back to int for computing result
long result=var1*var2; //Computing result
String newstr=String.valueOf(result); // Converting the final result back to String
int temp[]=new int[newstr.length()];// Creating the array to hold final result in it
int counter=0;
for (int i =newstr.length()-1;i>=0;i--) {
String nwresult="";
nwresult=nwresult+newstr.charAt(i); //reversing the final answer string
temp[counter++]= Integer.parseInt(nwresult); //Returning the final answer string by converting it to integer
}
return temp;
}
public static void main(String args[])
{
int[] numberA = {7, 3, 6, 2, 1};
int[] numberB = {7, 3, 3};
int array[]=times(numberA,numberB);
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
System.out.println("");
}
}