我看過其他線程,但沒有人回答我的問題。事實是,我認爲在我的情況下,問題不像其他問題。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
,但這似乎沒有幫助。
在此先感謝
'x.toString.reverse.toInt'使用純整型,而不是BigInt。因此崩潰。 – njzk2