我试图为项目euler开发代码 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
的总长度,但根据项目征集者的说法是错误的。如果有人可以查看我的代码并帮助我...
答案 0 :(得分:1)
看起来问题是'和'
这个词static String hundredValue="Hundred and";
对于诸如300(三百和)
之类的数字,不应该出现这种情况答案 1 :(得分:0)
除了克里斯托弗描述的"Hundred and"
问题之外,还有另一个问题:
您将int
传递给operateOn_2
,然后转换为字符串。这样,您在转换101
这样的数字时会错过前导零,这会转换为One Hundred and Eleven