알고리즘

[프로그래머스] 124 나라의 숫자

건뱅 2019. 5. 12.
반응형

<문제>

 

 

<작성코드>

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
32
33
34
35
36
37
38
39
40
41
42
43
 
import java.util.Scanner;
 
public class Solution12 { // 124나라
 
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (true) {
            System.out.println("변환 할 숫자를 입력하세요!");
            int natural = scan.nextInt();
            if (natural == 0) { // 0입력시 종료
                break;
            }
            System.out.println(natural + " ==> " + solution(natural));
        }
    }
 
    public static String solution(int n) {
        String answer = "";
 
        int r = 0// 3으로 나눈 나머지를 저장할 변수
        while (n != 0) {
            r = n % 3;
            n /= 3;
            if (r == 1) {
                answer = "1" + answer;
            } else if (r == 2) {
                answer = "2" + answer;
            } else if (r == 0) {
                answer = "4" + answer;
                if (n == 1) {
                    break;
                } else {
                    n -= 1;
                }
            }
        }
 
        return answer;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
 

 

 

<출력결과>

 

 처음에 결과가 역순으로 나와서 StringBuffer의 reverse 함수를 써서 작성해보았는데 콘솔창에는 잘 나오지만, 프로그래머스는 StringBuffer를 인식하지 못하는 것같았다(계속 런타임에러가 뜸... ㅠ)

생각 끝에 결과를 역순으로 나오지 않도록 코드를 수정하였다.

 

반응형

'알고리즘' 카테고리의 다른 글

[프로그래머스] 예산  (1) 2019.05.05
[프로그래머스] 모의고사  (1) 2019.04.30
[프로그래머스] 같은 숫자는 싫어~  (0) 2019.04.27
[프로그래머스] 콜라츠 추측  (0) 2019.04.26
[프로그래머스] 시저암호  (2) 2019.04.23

댓글