코딩응급실
프로그래머스: 콜라츠 추측 본문
class Solution {
public int solution(int number) {
long num = number; // 이거 없어서 계속 틀렸음... long으로 해야 큰 수일 때도 처리가능
int ans = 0;
while (num != 1) {
if (num % 2 == 0) {
num /= 2;
} else {
num = num * 3 + 1;
}
ans++;
if (ans == 500) {
return -1;
}
}
return ans;
}
public static void main(String[] args) {
int n = 626331;
Solution sol = new Solution();
int result = sol.solution(n);
System.out.println(result);
}
}
'Java' 카테고리의 다른 글
프로그래머스: 하샤드 수 (1) | 2024.01.21 |
---|---|
프로그래머스: 평균 구하기 (0) | 2024.01.21 |
프로그래머스: 최대공약수와 최소공배수 (1) | 2024.01.21 |
프로그래머스: 짝수와 홀수 (0) | 2024.01.21 |
프로그래머스: 제일 작은 수 제거하기 (0) | 2024.01.21 |