[Code Wars] Sum of Digits / Digital Root (C++)
https://www.codewars.com/kata/541c8630095125aba6000c00/train/cpp
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
문제 :
Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
번역:
디지털 루트(자릿수근)는 숫자의 모든 숫자의 재귀적 합입니다.
n이 주어지면, n의 자릿수의 합을 더합니다. 만약 그 값이 한 자리 수 이상이면, 한 자리 수가 나올 때까지 이런 식으로 계속 줄여나가세요. 입력은 음이 아닌 정수가 될 것입니다.
풀이 :
주어진 n이 한자릿 수 이상(10이상) 이라면 각 자리의 수를 더하고 한자리가 나올때까지 반복한다.
* 디지털 루트라는게 https://ko.wikipedia.org/wiki/%EC%9E%90%EB%A6%BF%EC%88%98%EA%B7%BC
자릿수근 - 위키백과, 우리 모두의 백과사전
위키백과, 우리 모두의 백과사전. 음이 아닌 정수의 자릿수근(영어: digital root, 반복적 자릿수합(repeated digital sum)이라고도 함)은 자릿수를 더하는 과정을 방금 구한 그 값의 자릿수합에서 자릿수
ko.wikipedia.org
우리나라 말로는 자릿수근이라고 한다.
int calcFunc(int n)
{
//주어진 수의 각 자리수를 더하는 함수
int total = 0;
while(n!=0)
{
total += n % 10;
n /= 10;
}
return total;
}
int digital_root(int n)
{
int reult =n;
//한자릿수 이상이라면 계속해서 반복한다.
while(reult>=10)
{
reult = calcFunc(reult);
}
//최종적으로 나온값을 출력
return reult;
}