[Programmers] #120906 - 자릿수 더하기 [Java][C++][Python]
[Programmers] #120906 - 자릿수 더하기 [Java][C++][Python]
1. 아이디어
정수 n의 각 자리 숫자를 모두 더하면 되는 문제다. n을 10으로 나눈 나머지로 마지막 자리 숫자를 얻고, n을 10으로 나눈 몫을 취하는 과정을 n이 0이 될 때까지 반복하여 더하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(D)$ | $O(1)$ |
($D$ = n의 자릿수 $\approx \log_{10} n$)
3. 코드
풀이 [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))
n을 문자열로 변환 후 sum으로 각 자리 숫자를 더하는 방식으로 해결했다.
This post is licensed under CC BY 4.0 by the author.