본문 바로가기
연습장

Sum of Digits / Digital Root

by anothel 2021. 10. 19.

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.

 

Examples

      16  --> 1 + 6 = 7
     942  --> 9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  --> 1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  --> 4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

 

Solution

int digital_root(int n) {
  int result = 0;
  int count = 0;

  while (0 < n) {
    result += n % 10;
    n /= 10;
    count++;
  }

  return 1 < count ? digital_root(result) : result;
}

 

__Anonymous__의 코드

int digital_root(int Z) {
    return --Z % 9 + 1;
}

 

후기

?????? 상당히 당혹스러웠다. 이렇게 한 줄로 마칠 수 있는 것이었다니.. 어떤 수학 공식 같은 건가? 저 아저씨는 대체 어떻게 이런 생각을 할 수 있었던 것일까? 정말 다시 한번 상당히 당혹스럽다.

 

(url: https://www.codewars.com/kata/541c8630095125aba6000c00)

 

728x90

'연습장' 카테고리의 다른 글

Bit Counting  (0) 2021.10.19
Convert string to camel case  (0) 2021.10.19
Find the odd int  (0) 2021.10.19
Split Strings  (0) 2021.10.19
Perimeter of squares in a rectangle  (0) 2021.10.19