[Programmers] #120834 - 외계행성의 나이 [Java][C++][Python]
정수 나이를 외계행성 알파벳 표기법으로 변환하는 워밍업 문제.
[Programmers] #120834 - 외계행성의 나이 [Java][C++][Python]
1. 아이디어
age를 10진법 자릿수 그대로 유지한 채, 각 자리 숫자(0~9)를 a부터 j까지의 알파벳 문자로 치환하면 되는 문제다. age를 10으로 나눈 나머지가 해당 자리 숫자이므로, 몫이 0이 될 때까지 나머지를 문자로 바꿔 누적하고 마지막에 순서를 뒤집으면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(D)$ | $O(D)$ |
$D$는 age의 자릿수($D = O(\log_{10} \text{age})$)다.
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public String solution(int age) {
StringBuilder sb = new StringBuilder();
while (age > 0) {
sb.append((char) (age % 10 + 'a'));
age /= 10;
}
return sb.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <bits/stdc++.h>
using namespace std;
string solution(int age) {
string s;
while (age > 0) {
s += (char)(age % 10 + 'a');
age /= 10;
}
reverse(s.begin(), s.end());
return s;
}
1
2
3
4
5
6
7
def solution(age):
s = ""
while age > 0:
s += chr(age % 10 + ord("a"))
age //= 10
return s[::-1]
This post is licensed under CC BY 4.0 by the author.