자릿수의 합

이세진·2022년 4월 15일
0

코테준비

목록 보기
6/87

생성일: 2022년 1월 6일 오후 5:12

구현 코드

# 자릿수의 합
import sys
sys.stdin = open("input.txt", "rt")
n = int(input())
numL = list(map(int, input().split()))
maxIndex = 0
maxSum = 0

def digit_sum(x):
    sum = 0
    for x in str(x):
        sum += int(x)
    return sum

for idx, num in enumerate(numL):
    sum = digit_sum(num)
    if sum > maxSum:
        maxSum = sum
        maxIndex = idx
print(numL[maxIndex])

모범 답안

import sys
sys.stdin=open("input.txt", "r")
def digit_sum(x):
    sum=0
    while x>0:
        sum+=x%10
        x=x//10
    return sum

n=int(input())
a=list(map(int, input().split()))
res=0
max=-2147000000
for x in a:
    tot=digit_sum(x)
    if tot>max:
        max=tot
        res=x
print(res)

차이점

  • 내가 구현한 코드에서는 정수의 모든 자릿수의 합을 구할 때, 해당 정수를 string으로 변환하고 for문을 돌려서 각 자릿수를 더하여 구하는 구조이다.
  • 모법 답안에서는 해당 정수를 10으로 나눈 나머지를 더하고 10으로 나눈 몫을 해당 정수를 변경하여 각 자릿수의 합을 구하는 방식이다.
profile
나중은 결코 오지 않는다.

0개의 댓글