[SWEA] 3750. Digit sum(python)
๐๋ฌธ์
๐ช์์ด๋์ด
1๋ฒ ๋ฐฉ๋ฒ
- ๋ฌธ์์ด์ฒ๋ฆฌ : ๋ฌธ์์ด -> ์ซ์๋ก๋ง๋ค๊ธฐ
- ๊ฐ ์๋ฆฌ์ ๋ํ๊ธฐ: tmp += n%10 ๊ฐ์ ๋ํ๊ธฐ -> tmp*=10 -> n=n//10
2๋ฒ ๋ฐฉ๋ฒ
- ๋ฌธ์์ด์ฒ๋ฆฌ
์ ๋ ฅ๋ฐ์ ๋ฌธ์์ด์ list๋ก ๋ง๋ ๋ค. - ๊ฐ ์๋ฆฌ์ ๋ํ๊ธฐ
list์ ์์๋ค์ int๋ก ํ๋ณํํ์ฌ ๋ํ๋ค. - ๋ฌธ์์ด ๊ธธ์ด ๊ฒ์ฌ
์ซ์๋ ๊ธธ์ด๋ฅผ ์ ์์์ผ๋ ๋ฌธ์์ด๋ก ํ๋ณํํ์ฌ ๊ธธ์ด๊ฐ 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.