Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- dynamic programming
- Data Structure
- Counting
- sorting
- Binary Search
- greedy
- hash table
- bit manipulation
- 구현
- Tree
- Method
- 파이썬
- Matrix
- 코테
- Binary Tree
- Stack
- array
- Math
- implement
- string
- SQL
- simulation
- Number Theory
- two pointers
- java
- geometry
- 코딩테스트
- Class
- 자바
- database
Archives
- Today
- Total
코린이의 소소한 공부노트
[프로그래머스/Lv.1] 3진법 뒤집기 본문
1. Input
1) 자연수 n
2. Output
1) n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수
3. Constraint
1) 1 <= n <= 100,000,000
4. Example
Input: n=45 -> Output: 7
설명: 45는 3진법으로 1200으로, 이를 뒤집은 0021은 10진법으로 7이다.
5. Code
1) 첫 코드(2022/??)
int answer = 0;
int num = n;
String reverse3 = "";
// 3진법으로 나타낸 수를 뒤집기
int l = 0;
while(num>=3) {
reverse3 += "" + num%3;
num /= 3;
l++;
}
reverse3 += "" + num;
l++;
// 뒤집어신 3진법 수를 10진법으로 바꾸기
String[] digit_s = reverse3.split("");
int x=0;
for(int i=0 ; i<l ; i++) {
x = Integer.parseInt(digit_s[i]);
if(x != 0)
answer += x * Math.pow(3,l-i-1);
}
return answer;
2) 좀더 간추려본 코드(2022/11/17)
String num = "";
while(n>=1){
num += String.valueOf(n%3);
n /= 3;
}
// n=0인 상태
for(int i=0 ; i<num.length() ; i++)
n += (num.charAt(i)-'0') * Math.pow(3, num.length()-1-i);
return n;
- 2번 코드가 1번보다 10배 이상 빠름
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[프로그래머스/Lv.1] 키패드 누르기 (0) | 2022.11.21 |
---|---|
[프로그래머스/Lv.1] 두 개 뽑아서 더하기 (0) | 2022.11.17 |
[프로그래머스/Lv.1] 내적 (0) | 2022.11.17 |
[프로그래머스/Lv.1] 신규 아이디 추천 (0) | 2022.11.15 |
[프로그래머스/Lv.1] 음양 더하기 (0) | 2022.11.15 |