끄적끄적 코딩일지

[Programmers]콜라츠 추측(난이도:★★★) 본문

알고리즘

[Programmers]콜라츠 추측(난이도:★★★)

BaekGyuHyeon 2022. 5. 16. 19:36

https://programmers.co.kr/learn/courses/30/lessons/12943

 

코딩테스트 연습 - 콜라츠 추측

1937년 Collatz란 사람에 의해 제기된 이 추측은, 주어진 수가 1이 될때까지 다음 작업을 반복하면, 모든 수를 1로 만들 수 있다는 추측입니다. 작업은 다음과 같습니다. 1-1. 입력된 수가 짝수라면 2

programmers.co.kr

class Solution {
    public int solution(int num) {
        return solutionA(num);
    }
    public int solutionA(int n){
        int counter = 0;
        // long으로 선언하여 각 단계 수행시 int 범위가 초과되어 오류가 나는것을 막을것
        long num = (long)n;
        while(num != 1L){
            counter++;
            if(num % 2L == 0L)
                num /= 2L;
            else{
                num *= 3L;
                num ++;
            }
            if(counter > 500)
                return -1;
        }
        return counter;
    }
}