Performance scala:更好的解决方案
问题:Performance scala:更好的解决方案,performance,scala,Performance,Scala,问题: 我们使用以下规则定义整数x的超位数: Iff x has only 1 digit, then its super digit is x. Otherwise, the super digit of x is equal to the super digit of the digit-sum of x. Here, digit-sum of a number is defined as the sum of its digits. For example, super digit of
我们使用以下规则定义整数x的超位数:
Iff x has only 1 digit, then its super digit is x.
Otherwise, the super digit of x is equal to the super digit of the digit-sum of x. Here, digit-sum of a number is defined as the sum of its digits.
For example, super digit of 9875 will be calculated as:
super-digit(9875) = super-digit(9+8+7+5)
= super-digit(29)
= super-digit(2+9)
= super-digit(11)
= super-digit(1+1)
= super-digit(2)
= 2.
You are given two numbers - n k. You have to calculate the super digit of P.
P is created when number n is concatenated k times. That is, if n = 123 and k = 3, then P = 123123123.
Input Format
Input will contain two space separated integers, n and k.
Output Format
Output the super digit of P, where P is created as described above.
Constraint
1≤n<10100000
1≤k≤105
Sample Input
148 3
Sample Output
3
Explanation
Here n = 148 and k = 3, so P = 148148148.
super-digit(P) = super-digit(148148148)
= super-digit(1+4+8+1+4+8+1+4+8)
= super-digit(39)
= super-digit(3+9)
= super-digit(12)
= super-digit(1+2)
= super-digit(3)
= 3.
一种简化方法是,您不必将被视为字符串的数字串联k次,而是可以从数字k*qs(n)开始(其中qs是将数字映射到其数字总和的函数,即qs(123)=1+2+3)。下面是一种更具功能性的编程方式。我不知道是否能做得比这更快
object Solution {
def qs(n: BigInt): BigInt = n.toString.foldLeft(BigInt(0))((n, ch) => n + (ch - '0').toInt)
def main(args: Array[String]) {
val input = scala.io.Source.stdin.getLines
val Array(n, k) = input.next.split(" ").map(BigInt(_))
println(Stream.iterate(k * qs(n))(qs(_)).find(_ < 10).get)
}
}
对象解决方案{
def qs(n:BigInt):BigInt=n.toString.foldLeft(BigInt(0))((n,ch)=>n+(ch-'0').toInt)
def main(参数:数组[字符串]){
val输入=scala.io.Source.stdin.getLines
val数组(n,k)=input.next.split(“”).map(BigInt(33;))
println(Stream.iterate(k*qs(n))(qs()).find(<10.get)
}
}
此解决方案是最佳解决方案竖起大拇指这里有Martin Odersky的Coursera课程,名为“Scala中的函数编程”,还有Runár的一本同名书,由manning出版(定期发售,9月22日。您可以使用促销代码DOTD092214C)。这两种方法都会让你达到中级水平,然后就是应用它。然后,您可以查看scalaz和Shapess的源代码,以提高技能。
object Solution {
def qs(n: BigInt): BigInt = n.toString.foldLeft(BigInt(0))((n, ch) => n + (ch - '0').toInt)
def main(args: Array[String]) {
val input = scala.io.Source.stdin.getLines
val Array(n, k) = input.next.split(" ").map(BigInt(_))
println(Stream.iterate(k * qs(n))(qs(_)).find(_ < 10).get)
}
}