2011-07-26 62 views
-2

我曾嘗試開發代碼項目歐拉 Problem 17項目歐拉數字問題

我已經成功地寫了一個Java程序,並出現預期的輸出。但是網上法官說這是錯誤的答案。看看我的代碼:

package projectEuler; 

import java.util.*; 
public class Problem17 { 

/** 
* @param args 
*/ 
static String []units={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; 

static String []special={"Ten","Eleven","Twelve","Thirteen","Fourteen", 
        "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; 

static String []tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy", 
       "Eighty","Ninety"}; 

static String hundredValue="Hundred and"; 

public static void main(String[] args) 
{  
long totalLength=0; 
for(int currentNumber=1;currentNumber<=1000;currentNumber++) 
{ 
    String currentWord=getWords(currentNumber); 
    // System.out.println(currentNumber+"->"+currentWord.replaceAll(" ","")); 
    totalLength+=currentWord.replaceAll(" ","").length(); 

} 
System.out.print("The total length of all the word is :"+totalLength); 
/*Scanner input = new Scanner(System.in); 
System.out.print("Enter a number :"); 
int num = input.nextInt(); 
System.out.print(getWords(num));*/ 
} 

public static String getWords(int num) 
{  
    //Find the equivalent word and return it 

    String wordValue=""; 

    switch(String.valueOf(num).length()) 
    { 
    case 1: 
     wordValue=operateOn_1(num); 
    break; 

    case 2: 
     wordValue= operateOn_2(num); 
    break; 

    case 3: 
     wordValue= operateOn_3(num); 
    break; 

    default: 
     wordValue="One Thousand"; 
    } 
    return wordValue; 
} 

public static String operateOn_3(int num) 
{ 

    String result=""; 
    result= Problem17.units[num/100]+" "+ 
      Problem17.hundredValue+" "+ 
     operateOn_2(Integer.parseInt((String.valueOf(num).substring(1)))); 
    return result; 
} 

public static String operateOn_2(int num) 
{ 
    String result=""; 
    if(String.valueOf(num).charAt(0)=='1') 
    { 
    result=Problem17.special[num%10]; 
    } 
    else 
    {   
     result=Problem17.tens[Integer.parseInt(String.valueOf((String.valueOf(num)).charAt(0)))]; 
     result+=" "+operateOn_1(num%10); 
    } 
    return result; 
} 

public static String operateOn_1(int num) 
{ 

    return (Problem17.units[num]); 
} 

} 

總長度程序發現的21592但根據項目歐拉是錯誤的。如果有任何可以看看我的代碼,並請幫我...

+2

-1如果網上裁判說這是錯誤的,那麼這是錯誤的,而你的任務是找到你的錯誤。詢問Stackoverflow是作弊的。是的,它很難,但是如果你自己做,當你最終做對時你會更滿意。 – starblue

回答

1

它看起來像這個問題是不應該的號碼如300出現的話「和」

static String hundredValue="Hundred and"; 

(三百)

+0

@Christopher,非常感謝您的快速回復。優秀的幫助:) – kunaguvarun

+0

@Peter完成和完成(不想標誌或downvote,所以我留下了評論)。給克里斯托弗+1順便說一句。 – cwallenpoole

+0

謝謝你們兩位。這樣一個友好的社區! – Christopher

0

除了由克里斯托弗描述的"Hundred and" - 問題,還有一個問題:

你傳遞一個intoperateOn_2,然後您可以轉換爲字符串。這樣,當轉換101這樣的數字時,如果轉換爲One Hundred and Eleven