Post

[SWEA] 3750. Digit sum(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

1๋ฒˆ ๋ฐฉ๋ฒ•

  1. ๋ฌธ์ž์—ด์ฒ˜๋ฆฌ : ๋ฌธ์ž์—ด -> ์ˆซ์ž๋กœ๋งŒ๋“ค๊ธฐ
  2. ๊ฐ ์ž๋ฆฌ์ˆ˜ ๋”ํ•˜๊ธฐ: tmp += n%10 ๊ฐ’์„ ๋”ํ•˜๊ธฐ -> tmp*=10 -> n=n//10

2๋ฒˆ ๋ฐฉ๋ฒ•

  1. ๋ฌธ์ž์—ด์ฒ˜๋ฆฌ
    ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด์„ list๋กœ ๋งŒ๋“ ๋‹ค.
  2. ๊ฐ ์ž๋ฆฌ์ˆ˜ ๋”ํ•˜๊ธฐ
    list์˜ ์š”์†Œ๋“ค์„ int๋กœ ํ˜•๋ณ€ํ™˜ํ•˜์—ฌ ๋”ํ•œ๋‹ค.
  3. ๋ฌธ์ž์—ด ๊ธธ์ด ๊ฒ€์‚ฌ
    ์ˆซ์ž๋Š” ๊ธธ์ด๋ฅผ ์•Œ ์ˆ˜์—†์œผ๋‹ˆ ๋ฌธ์ž์—ด๋กœ ํ˜•๋ณ€ํ™˜ํ•˜์—ฌ ๊ธธ์ด๊ฐ€ 1์ด ๋  ๋•Œ๊นŒ์ง€ 2๋ฅผ ๋ฐ˜๋ณตํ•œ๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def func(num):
    tmp=0
    while num:
        tmp += num%10
        num//=10
    num=tmp
    if num//10==0: return num
    return func(num)

T = int(input())
li=[]
for tc in range(1,T+1):
    li.append(int(input()))

for i, num in enumerate(li):
    answer = func(num)
    print('#{} {}'.format(i+1,answer))

1
2
3
4
5
6
7
8
9
10
T = int(input())
li=[]
for tc in range(1,T+1):
    li.append(input())

for i, num in enumerate(li):
    while len(num)!=1:
        num = sum(map(int,num))
        num = str(num)
    print('#{} {}'.format(i+1,num))
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.