Recursive Digit Sum
HackerRank 问题: Recursive Digit Sum
Categories:
Question
We define super digit of an integer x
using the following rules:
Given an integer, we need to find the super digit of the integer.
- If
x
has only1
digit, then its super digit isx
. - Otherwise, the super digit of
x
is equal to the super digit of the sum of the digits ofx
.
Answer
<?php
/*
* Complete the 'superDigit' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING n
* 2. INTEGER k
*/
function superDigit($number_string, $number_string_duplicate_times) {
// sum all number
$number_array = str_split($number_string);
$super_digit = array_sum($number_array) * $number_string_duplicate_times;
if ($super_digit > 9 OR $super_digit < -9) {
// super digit not found, continue to find
return superDigit($super_digit, 1);
}
return $super_digit;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$first_multiple_input = explode(' ', rtrim(fgets(STDIN)));
$n = $first_multiple_input[0];
$k = intval($first_multiple_input[1]);
$result = superDigit($n, $k);
fwrite($fptr, $result . "\n");
fclose($fptr);