我目前正在学习Scala,而我正尝试用它来解决一些欧拉挑战。
我在回答第8次挑战时遇到了一些问题,我真的不知道我的错误在哪里。
object Product{
def main(args: Array[String]): Unit = {
var s = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
var len = 13;
var bestSet = s.substring(0,len);
var currentSet = "";
var i = 0;
var compare = 0;
for(i <- 1 until s.length - len){
currentSet = s.substring(i,i+len);
compare = compareBlocks(bestSet,currentSet);
if(compare == 1) bestSet = currentSet;
}
println(v1);
var result = 1L;
var c = ' ';
for(c <- v1.toCharArray){
result = result * c.asDigit.toLong;
}
println(result);
}
def compareBlocks(block1: String, block2: String): Int = {
var i = 0;
var v1 = 0;
var v2 = 0;
if((block1 contains "0") && !(block2 contains "0")) return 1;
if(!(block1 contains "0") && (block2 contains "0")) return -1;
if((block1 contains "0") && (block2 contains "0")) return 0;
var chars = block1.toCharArray;
for(i <- 0 until chars.length){
v1 = v1 + chars(i).asDigit;
}
chars = block2.toCharArray;
for(i <- 0 until chars.length)
{
v2 = v2 + chars(i).asDigit;
}
if(v1 < v2) return 1;
if(v2 < v1) return -1;
return 0;
}
}
我的结果是:
9753697817977&lt; - 数字序列
8821658160&lt; - 乘法
答案 0 :(得分:3)
使用Euler Project来挑战自己并学习一门新语言是个不错的主意,但只是提出正确的答案并不意味着你能很好地使用这门语言。 / p>
从您的代码中可以明显看出,您尚未学习惯用的Scala。您是否会惊讶地发现只需一行代码即可从100个字符的输入字符串中计算出所需的产品?那一行代码将:
Int
)有一个方便的小web site解决了Scala中的Euler挑战。我建议您每次解决欧拉问题时,请将您的代码与该网站上的代码进行比较。 (但要小心。现在很容易看到你尚未解决的解决方案。)