3진법 뒤집기
문제
https://programmers.co.kr/learn/courses/30/lessons/68935
코딩테스트 연습 - 3진법 뒤집기
자연수 n이 매개변수로 주어집니다. n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요. 제한사항 n은 1 이상 100,000,000 이하인 자연수
programmers.co.kr
코드
import java.util.ArrayList;
class Solution {
public int solution(int n) {
int result = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
// 10진법 -> 3진법 변환
do {
if (n < 3) {
list.add(n);
break;
}
list.add(n % 3);
n /= 3;
} while (true);
// 앞뒤 반전(3진법)
// System.out.println(list.toString());
for (int i = 0; i < list.size(); i++) {
// Math.pow(밑, 지수)
result += Math.pow(3, (list.size() - (i + 1))) * list.get(i);
}
return result;
}
}
'프로그래머스 > LEVEL 1' 카테고리의 다른 글
[프로그래머스/LEVEL1] 같은 숫자는 싫어 (0) | 2022.01.17 |
---|---|
[프로그래머스/LEVEL1] 최소직사각형 (0) | 2022.01.17 |
[프로그래머스/LEVEL1] 하샤드 수 (0) | 2022.01.17 |
[프로그래머스/LEVEL1] 콜라츠 추측 (0) | 2022.01.17 |
[프로그래머스/LEVEL1] 제일 작은 수 제거하기 (0) | 2022.01.17 |