Post

[Programmers] #120906 - 자릿수 더하기 [Java][C++][Python]

[Programmers] #120906 - 자릿수 더하기 [Java][C++][Python]

문제 링크


1. 아이디어

정수의 각 자리 숫자를 더하는 문제다. 10으로 나눈 나머지가 가장 낮은 자리 숫자이고 몫이 그 자리를 떼어 낸 수라서, 수가 0이 될 때까지 나머지를 더하며 몫으로 넘어가면 모든 자리를 한 번씩 거친다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int solution(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }

        return sum;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;

int solution(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }

    return sum;
}
1
2
def solution(n):
    return sum(int(d) for d in str(n))

This post is licensed under CC BY 4.0 by the author.