[programmers]콜라츠 추측(C#)

김근면·2022년 7월 16일
0

Programmers

목록 보기
5/5
post-thumbnail

🔗Link

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

💻Code

✍풀이

public class Solution
    {
        public int solution(int num)
        {
        // 입력받은 int형의 num을 long으로 변환해준다.
            long temp = num;
            // 반복 횟수를 측정
            int answer = 0;
            // 숫자가 1이될때까지 반복한다.
            while (temp != 1)
            {
            // 반복횟수를 1 올려준다.
                ++answer;
                
                // 숫자가 짝수면 나누기 2 , 홀수면 3곱하고 1을 더함
                temp = temp % 2 == 0 ? temp / 2 : temp * 3 + 1;
                
                // 만약 반복숫자가 500이 넘어버리면
                if (answer > 500)
                {
                    return -1;
                }
            }
            // 몇번 반복했는지 리턴
            return answer;
        }
    }

📌Solution

풀이 참고자료
반복문 참고자료
정수형 참고자료

profile
cheer about the man right next to you

0개의 댓글