2014-05-06 30 views
0

我看過其他線程,但沒有人回答我的問題。事實是,我認爲在我的情況下,問題不像其他問題。Scala - 線程「main」中的異常java.lang.NumberFormatException

下面是我試圖解決這個問題的鏈接:http://projecteuler.net/problem=55

我相信算法是正確的,但我懷疑的是,有一些什麼斯卡拉可以轉換爲字符串回事。我不知道。這裏是我的代碼:

package projecteuler55 

object PE55 extends App { 



def rev (x :BigInt) : BigInt = { 
    x.toString.reverse.toInt 
} 



def notPalindrome (x:BigInt) : Boolean = { 
    if (x != rev(x)) true else false 
} 

def test (x:BigInt , steps:Int) : Boolean = { 

    if (steps > 50) true 
    else if (notPalindrome(x) == false) false 
    else test (x + rev(x) , steps +1) 
    } 

var lychrel = 0 
for (i<-10 until 10000){ 
    if (test(i+rev(i),0)) lychrel += 1 
} 
println(lychrel) 

} 

,我得到的錯誤是這樣的:

Exception in thread "main" java.lang.NumberFormatException: For input string: "2284457131" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:495) 
    at java.lang.Integer.parseInt(Integer.java:527) 
    at scala.collection.immutable.StringLike$class.toInt(StringLike.scala:229) 
    at scala.collection.immutable.StringOps.toInt(StringOps.scala:31) 
    at projecteuler55.PE55$.rev(PE55.scala:8) 
    at projecteuler55.PE55$.notPalindrome(PE55.scala:14) 
    at projecteuler55.PE55$.test(PE55.scala:20) 
    at projecteuler55.PE55$$anonfun$1.apply$mcVI$sp(PE55.scala:26) 
    at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:141) 
    at projecteuler55.PE55$delayedInit$body.apply(PE55.scala:25) 
    at scala.Function0$class.apply$mcV$sp(Function0.scala:40) 
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) 
    at scala.App$$anonfun$main$1.apply(App.scala:71) 
    at scala.App$$anonfun$main$1.apply(App.scala:71) 
    at scala.collection.immutable.List.foreach(List.scala:318) 
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32) 
    at scala.App$class.main(App.scala:71) 
    at projecteuler55.PE55$.main(PE55.scala:3) 
    at projecteuler55.PE55.main(PE55.scala) 

爲什麼會出現這種情況?如果發生溢出,我也使用BigInt,但這似乎沒有幫助。

在此先感謝

+0

'x.toString.reverse.toInt'使用純整型,而不是BigInt。因此崩潰。 – njzk2

回答

3

toInt預計可以解析到適合經常Int,這2284457131不能字符串。你想使用BigInt(x.toString.reverse)

+0

哦,我不知道你可以像這樣使用BigInt。這就是我一直在尋找的東西。謝謝! – billpcs

相關問題