bearbrick 2022. 5. 16. 12:00

*이 풀이는 인프런: 파이썬 알고리즘 문제풀이 강좌에 기반하였습니다.

 

 

 

내 풀이

 

1. 인자를 10으로 나눔으로써 나오는 나머지를 통해 자릿 수를 구한다.

2. while문을 이용해서 각 자릿 수를 모두 구한다.

3. for문을 통해 입력받은 숫자들의 각 자릿 수 합을 구하고, 각 값들을 비교함으로써 가장 높은 합을 가진 숫자를 구한다.

 

import sys
#sys.stdin=open("input.txt", "r")

t= int(input())
arr=list(map(int, input().split()))

def digit_sum(x):
    sum=0
    while True:
        digit = x%10
        x = x//10
        sum+=digit
        if x < 10:
            return sum+x

max = 0
for x in arr:
    sum = digit_sum(x)
    if max < sum:
        max = sum
        res = x

print(res)

 

 

 

강사님 풀이 

 

1. 정수를 통해 각 자릿 수의 합 계산

 

import sys
sys.stdin=open("input.txt", "r")

n= int(input())
a=list(map(int, input().split()))

def degit_sum(x):
    sum=0
    while x>0:
        sum+=x%10
        x=x//10
    return sum

max=-2147000000
for x in a:
    tot=degit_sum(x)
    if tot>max:
        max=tot
        res=x
        
print(res)

 

 

 

2. 문자를 통해 각 자릿 수의 합 계산

 

import sys
sys.stdin=open("input.txt", "r")

n= int(input())
a=list(map(int, input().split()))

def degit_sum(x):
    sum=0
    for i in str(x):  # i가 문자열에서 문자 하나 하나 접근
        sum+=int(i)
    return sum
        
max=-2147000000
for x in a:
    tot=degit_sum(x)
    if tot>max:
        max=tot
        res=x

print(res)

 

 

 

배운 점

 

1. 특정 값을 재사용할 일이 없으면 변수에 저장하지 않는다.

2. 정수를 문자열로 변환해서 정수의 각 자릿 수에 접근할 수 있다.