ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • section2.6 자릿수의 합
    알고리즘 2022. 10. 22. 17:53

    N개의 자연수가 입력되면 각 자연수의 자릿수의 합을 구하고, 그 합이 최대인 자연수를 출력하는 프로그램을 작성하세요. 각 자연수의 자릿수의 합을 구하는 함수를 def digit_sum(x)를 꼭 작성해서 프로그래밍하세요.

     

     

     

    import sys
    sys.stdin = open("input.txt", "rt")
    n = int(input())
    nList = list(map(str, input().split()))
    cntList = [0]*n
    max = -247000000
    
    '''
    이중 for문 사용, cnt 리스트
    1 for문 > nList 하나씩 접근
            > 2 for문 > len으로 자리수 합 구하기, cntList에 넣기
    cntList 중 max 구하고 숫자 출력
    '''
    
    def digit_sum(x):
        sum = 0
        for i in range(len(x)):
            sum += int(x[i:i+1])
        return sum
    
    for i in range(n):
        cntList[i] += digit_sum(nList[i])
    
    for i in range(n):
        if max < cntList[i]:
            max = cntList[i]
    
    for i in range(n):
        if max == cntList[i]:
            print(nList[i])
            break

     

    정답이지만 풀이법을 보니 파이썬에서는 아래와 같이 str(x)를 조금 더 쉽게 쓸 수 있었다

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

     

     

    import sys
    sys.stdin = open("input.txt", "rt")
    n = int(input())
    a = list(map(int, input().split()))
    max = -214700000
    
    def digit_sum(x):
        sum=0
        while x>0:
            sum+=x%10
            x=x//10
        return sum
    
    for x in a:
        tot=digit_sum(x)
        if tot>max:
            max=tot
            res=x
    print(res)
     

     

    728x90

    '알고리즘' 카테고리의 다른 글

    section2.8 뒤집은 소수  (0) 2022.10.24
    section2.7 소수(에라토스테네스 체)  (0) 2022.10.24
    section2.5 정다면체  (0) 2022.10.22
    section2.4 대표값  (0) 2022.10.22
    section2. 최솟값 구하기  (1) 2022.10.21
Designed by Tistory.