2016-12-24 47 views
0

編程你好的人,乘以大的數字(陣列),而Java的API

號碼向後存儲在爲小的,可能的整數數組:

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; 
} 

由於12637 X 337 = 4258669返回的數組應該是這樣的:

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(int[] fromInt(int)


號(數組)感謝

+7

什麼你有沒有嘗試過(代碼明智,你自己)到目前爲止?這讀取像一個家庭作業 – Rogue

+0

你可以嘗試並提取一個'int'值,即。使用循環從陣列中提取「12637」。這是你想要的嗎 ? –

+0

@Rogue其實我試圖修改「添加」 - 函數,以適應乘,但我沒能產生具有動態長度的數組。我也試圖通過在零打滑模仿乘以筆/紙數的步驟(如在小學)總結最終產品 – TheRedRabbit

回答

0
+1

雖然鏈接可能導致的解決方案,它不是寫答案,看到的鏈接可以得到破好。 – ItamarG3

+0

這些都是衆所周知的算法,所以如果鏈接被破壞,你可以在其他地方找到它們。 – cproeller

+0

在這種情況下,你是正確的。但是,這通常不是這種情況。 – ItamarG3

0

我有這個程序,你已經張貼在你的問題,這將創造的結果,正如你所指定我沒有使用任何Java API如ArrayList的,代碼爲:

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(""); 

    } 

} 
+0

我認爲這裏的目標是將字符串乘以不轉換爲整數。 – rcgldr