2013-01-15 56 views
-2

我試圖解決這個問題,但想不出拿出什麼...彙總數

,我們將命名一批「彙總數據」如果這個數字具有以下屬性: 就像斐波那契數 1 ,1,2,3,5,8,13 .....

數字中的數字可以分成幾個部分,後面的部分是前幾部分的總和。

like 112358, because 1+1=2, 1+2=3, 2+3=5, 3+5=8 
122436, because 12+24=36 
1299111210, because 12+99=111, 99+111=210 
112112224, because 112+112=224 

對不完整的問題,我們需要編寫函數來測試一個數字是否被聚合? 任何想法請幫助

+1

你可以說你的問題是一個問題嗎?現在很難回答。 – BlackVegetable

+0

這裏沒問題, –

+0

增加了這個問題... –

回答

1

如果你被困住了,試着把問題分解成更簡單的可解決的塊。例如,爲了讓你開始:

/** 
* Returns true if the provided number is an aggregated number 
* 
* @param potentialAggregatedNumber The number to check. 
*/ 
boolean isAggregated (potentialAggregatedNumber){ 
    for(numDigits=1; numDigits <= (potentialAggregatedNumber.length/2); numDigits++){ 
     if(isAggregatedForFirstNumberLength(potentialAggregatedNumber, numDigits) { 
      return true; 
     } 
    } 
    return false; 
} 

/** 
    * Returns true if aggregated number when the first number has numDigits digits. 
    * 
    * @param potentialAggregatedNumber The number to check. 
    * @param numDigits The number of digits the first sub-number should have. 
    */ 
boolean isAggregatedForFirstNumberLength(potentialAggregatedNumber, numDigits){ 
    //your code 
} 
+0

這並沒有多大幫助。除以3是錯誤的。 – Dialecticus

+0

@Dialecticus:要成爲一個「聚合數字」,它必須至少有三個部分:兩個數字要加,一個作爲總和。我假設第二個數字的價值相等或更高,但我認爲「11011」可能是他的定義中的一個總數,現在我想到了它。我已經修改過來反映這一點。 – Briguy37

+0

@Dialecticus:另外,我的意圖是讓他指向正確的方向,而不是給他完整的答案。 'isAggregatedForFirstNumberLength'絕對是一個比'isAggregated'更簡單的函數,所以如果他繼續沿着定義對更簡單更簡單的函數的需求的路徑,Sree最終會達到一個有效的算法。去Sree吧! :) – Briguy37

0

當你有前兩個數字的位數,你有你需要檢查聚合的數字的一切。您只需爲前兩個數字生成所有有效數字組合。數字總和不應大於所有數字的一半,因爲否則第三個數字(前兩個數字的總和)將不適合總數的其餘部分。生成數字號碼的所有組合的最佳方式是這樣的嵌套循環:爲貫徹落實CheckAggregateNumber功能

for (int both_digits = 2; both_digits * 2 <= total_digits; both_digits++) 
{ 
    for (int first_digit = 1; first_digit < both_digits; first_digit++) 
    { 
    int second_digit = both_digits - first_digit; 

    if (CheckAggregateNumber(aggregate_number, first_digit, second_digit)) 
     return true; 
    } 
} 

最簡單的方法是通過字符串比較。首先將聚合數字轉換爲字符串。然後在循環中生成應該是使用第一個和第二個數字的聚合數的子串的字符串,並將這些子字符串與聚合數的適當部分進行比較。如果一切都結束,直到結束返回true,否則返回false。這裏有一些僞代碼:

aggregate_string = aggregate_number as string; 
first_number = aggregate_string.Substring(0, first_digit) as int; 
second_number = aggregate_string.Substring(first_digit, second_digit) as int; 
index_on_aggregate = first_digit + second_digit; 

begin loop 
    new_number = first_number + second_number; 
    new_string = new_number as string; 

    if (new_string == aggregate_string.Substring(index_on_aggregate, new_string.Length) 
    return false; 

    first_number = second_number; 
    second_number = new_number; 
    index_on_aggregate = index_on_aggregate + new_string.Length; 

    if (index_on_aggregate == aggregate_string.Length) 
    return true; 
end loop