[Programmers] #12931 - 자릿수 더하기 [Java][C++][Python]
[Programmers] #12931 - 자릿수 더하기 [Java][C++][Python]
1. 아이디어
자연수 $N$의 각 자릿수를 더하는 문제인데, 10으로 나눈 나머지가 가장 낮은 자리이고 10으로 나눈 몫은 그 자리를 떼어 낸 수이므로 $N$이 0이 될 때까지 이를 반복하면 모든 자리를 빠짐없이 한 번씩 더하게 된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
public 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.