Home>

I want to convert python3 code to ruby.

def digitSum (n):
    # Determine number of digits
    if len (str (n)) is 1:
        return n
    dst = sum (list (map (int, str (n))))
    return digitSum (dst)

if __name__ == "__main__":
    n = 12345
    result = digitSum (n)
    print (int (result)) # 15


The output will be 6.

I tried to write in ruby, but I didn't understand well.

gets;a = gets.split.map (&: to_i) .inject (: *)
b = a.to_s.chars.map (&: to_i) .sum
p b.to_s.chars.map (&: to_i) .sum if b.to_s.size>= 1


I don't know how to use if modifier or while modifier.
I don't even know about recursion ...

Reference
How to find the sum of integer digits | Python-suzu6
https://www.suzu6.net/posts/30/
"Repeat the calculation until the specified number of digits is reached.

"" "
Calculate the total value for each digit
Repeat until the number of digits reaches 1
"" "
def digitSum (n):

Judge the number of digits

if len (str (n)) is 1:
return n
dst = sum (list (map (int, str (n))))
return digitSum (dst)

ifname== "main":
n = 12345
result = digitSum (n)

print (int (result)) # 15 "

Additional
25
39532 77816 39481 47622 16931 32489 56334 22924 71026 26191 10335 11788 77781 95817 89898 65677 23947 98056 61947 55674 21198 52752 21623 62340 82524
When
9
I want to put out
18 is output

yukicoder
https://yukicoder.me/problems/no/933/test#Test06.txt
"39532 77816 39481 47622 16931 32489 56334 22924 71026 26191 10335 11788 77781 95817 89898 65677 23947 98056 61947 55674 21198 52752 21623 62340 82524
"

  • Answer # 1

    Another solution is to use the method of "leave the remainder divided by 9 (however, if it is 0, it will be 9 unless the original is 0)".

    Number root-Wikipedia

  • Answer # 2

    a = a.digits.sum while a.digits.size! = 1
    p a

Related articles