Super Digit – HackerRank Solution

In this post, we will solve Super Digit HackerRank Solution. This problem (Super Digit) is a part of HackerRank Functional Programming series.

Contents

Task

We define super digit of an integer x using the following rules:

  • If 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 and 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

Output the super digit of P, where P is created as described above.

Sample Input 0

148 3

Sample Output 0

3

Explanation 0

Here n = 148 and k = 3, so P = 148148148.

=== codingbroz.com_728x90 (#88864) ===
=== codingbroz.com_728x90 (#88864) ===
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.

Solution – Super Digit – HackerRank Solution

Scala

import java.util.Scanner

object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)

    val n = sc.next
    val k = sc.nextInt

    sc.close()

    val nDigit = superOnce(n)
    println(superDigit((nDigit.toLong * k).toString))
  }

  def superDigit(s: Seq[Char]): Int = {
    val sum = superOnce(s)
    if (sum < 10) sum else superOnce(sum.toString)
  }

  def superOnce(s: Seq[Char]): Int = s.foldLeft(0)((acc, c) => acc + c - '0')
}

Note: This problem (Super Digit) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published.