[HackerRank] Recursive Digit Sum

JAMM·2023년 3월 17일
0

HackerRank

목록 보기
1/7
post-thumbnail

Problem

Code

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'superDigit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. STRING n
#  2. INTEGER k
#

def superDigit(n, k):
    # Write your code here
    
    '''
    Step 1.
    주어진 n, k를 이용하여 init number p의 각 digit의 합 구하기
    '''
    p = sum(list(map(int, n))) * k
    '''
    Step 2.
    p의 각 digit의 합이 한 자릿수가 될 때 까지, 각 digit의 합을 구하기
    '''
    while True:
        if len(str(p)) == 1:
            return p
        p = sum(list(map(int, str(p))))
        

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    first_multiple_input = input().rstrip().split()

    n = first_multiple_input[0]

    k = int(first_multiple_input[1])

    result = superDigit(n, k)

    fptr.write(str(result) + '\n')

    fptr.close()

Reference

HackerRank - Recursive Digit Sum

0개의 댓글