嗨,我是 Scala 函数式编程方法的新手。我想在我的函数中输入一个数字并检查它是否是一个好数字。 如果一个数字的每个数字都大于该数字右侧的数字之和,则该数字是一个好数字。 例如: 9620 相当于 (2 > 0, 6 > 2+0, 9 > 6+2+0) 我用来解决这个问题的步骤是
1. converting a number to string and reversing it
2. storing all digits of the reversed number as elements of a list
3. applying for loop from i equals 1 to length of number - 1
4. calculating sum of first i digits as num2
5. extracting ith digit from the list as digit1 which is one digit ahead of the first i numbers for which we calculated sum because list starts from zero.
6. comparing output of 4th and 5th step. if num1 is greater than num2 then we will break the for loop and come out of the loop to print it is not a good number.
请在下面找到我的代码
val num1 = 9521.toString.reverse
val list1 = num1.map(_.todigit).toList
for (i <- 1 to num1.length - 1) {
val num2 = num1.take(i).map(_.toDigits) sum
val digit1 = list1(i)
if (num2 > digit1) {
print("number is not a good number")
break
}
}
我知道这不是解决这个问题的最优化方法。另外,我正在寻找一种使用尾递归进行编码的方法,其中我传递两个数字并获得落在这两个数字之间的所有好数字。 这可以以更优化的方式完成吗? 提前致谢!
最佳答案
无需字符串
转换。
val n = 9620
val isGood = Stream.iterate(n)(_/10)
.takeWhile(_>0)
.map(_%10)
.foldLeft((true,-1)){ case ((bool,sum),digit) =>
(bool && digit > sum, sum+digit)
}._1
关于scala - 判断一个数字是否是 scala 中的好数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389096/