반응형
<문제>
<코드>
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
44
45
46
47
48
49
50
51
52
|
package com.java.programers;
public class Solution6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("숫자를 입력하세요");
int number = scanner.nextInt();
if (number == 0) {
break;
}
System.out.println("반복횟수: " + solution(number));
}
}
public static int solution(int num) {
int answer = 0;
long cnt = num;
for (answer = 0; answer < 500;) {
//입력값이 1일 때
if (cnt == 1) {
break;
}
if (cnt % 2 == 0) {
// 짝수일때
cnt /= 2;
answer++;
if (cnt == 1) {
break;
}
} else if (cnt % 2 == 1) {
// 홀수일때
cnt = cnt * 3 + 1;
answer++;
}
}
if (answer == 500) {
return -1;
} else {
return answer;
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
|
<결과 화면>
문제를 풀면서 큰수를 입력할 시 에러가 났는데 이는 int => long 으로 바꾸어 선언하여 해결하였고,
처음에 테스트 13번이 통과가 안되어서 고민했는데, 입력값이 1인경우를 생각을 하여 조건을 넣어주었더니 해결되었다.
반응형
'알고리즘' 카테고리의 다른 글
[프로그래머스] 모의고사 (1) | 2019.04.30 |
---|---|
[프로그래머스] 같은 숫자는 싫어~ (0) | 2019.04.27 |
[프로그래머스] 시저암호 (2) | 2019.04.23 |
[프로그래머스] 나누어 떨어지는 숫자 배열 (4) | 2019.04.18 |
[프로그래머스] 두 정수 사이의 합 (2) | 2019.04.17 |
댓글