scala - 判断一个数字是否是 scala 中的好数字

标签 scala functional-programming

嗨,我是 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/

相关文章:

json - 在scala中使用spray编写一个简单的json REST服务器

haskell - 递归排序非连续列表到连续列表列表

javascript - 如何从对象数组中按数组选取元素

javascript - LazyEvaluation 的性能优势究竟从何而来?

clojure - 一旦达到所需的累积量,如何停止reduce函数处理列表?

multithreading - 如何找到每个 future 在 Scala 中花费的时间?

scala - PySpark 到 Scala : UDF with StructType, GenericRowWithSchema 无法转换为 org.apache.spark.sql.Column

oop - 在 OCaml 中即时创建对象

scala - 控制配置设置 Apache Spark UTF 编码以写入为 saveAsTextFile

java - 编译 Spark 类时出现 "Eclipse Plugin for Scala"错误