[Programmers] 120906번 - 자릿수 더하기 [Java][C++]
[Programmers] 120906번 - 자릿수 더하기 [Java][C++]
1. 아이디어
정수 n의 각 자리 숫자의 합을 return하는 문제로 각 자릿수는 10으로 나눈 나머지를 구하고 10으로 나눈 몫을 구한 후, 다시 몫을 10으로 나눈 나머지를 구하는 과정을 반복하면 모두 구할 수 있다.
2. 복잡도
| 시간복잡도 | 공간복잡도 |
|---|---|
| $O(\log n)$ | $O(1)$ |
n = 입력 정수(자릿수 개수는 log n에 비례)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int solution(int n) {
int ans = 0;
while (n > 0) {
ans += n % 10;
n /= 10;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;
int solution(int n) {
int ans = 0;
while (n) {
ans += n % 10;
n /= 10;
}
return ans;
}
This post is licensed under CC BY 4.0 by the author.