본문 바로가기

프로그래밍/알고리즘(자바)

콜라츠 추측 Level 2 #삼항연산자

콜라츠 추측 Level 2

https://programmers.co.kr/learn/challenge_codes/13

class Collatz {
    public int collatz(int num) {
        int answer = 0;
        while(answer < 500){
            num = (num%2==0) ? (num /= 2) : (num = num*3+1);
            answer++;
            if (num == 1)
                return answer;
        } 
        return -1;
    }

    // 아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void main(String[] args) {
        Collatz c = new Collatz();
        int ex = 1056935;
        System.out.println(c.collatz(ex));
    }
}