Posts [프로그래머스] 콜라츠 추측 / C++
Post
Cancel

[프로그래머스] 콜라츠 추측 / C++


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


  1. 연산 할 때 int 범위를 벗어나므로 long long으로 자료형 변환해줍니다.

  2. 입력된 수가 짝수면 2로 나눕니다.

  3. 입력된 수가 홀수면 3을 곱하고 1을 더합니다.

  4. n이 1이되거나, 연산 횟수가 500일 때 반복문을 탈출합니다.


소스 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>

using namespace std;

int solution(int num){
    long long n = num;
    int answer = 0;
    
    while(true){
        
        if(n==1)
            break;
        
        n%2 == 0 ? n/=2 : n = 3*n + 1;
        answer++;
        
        if(answer==500){
            answer=-1;
            break;
        }

    }
    return answer;
}



This post is licensed under CC BY 4.0 by the author.

[프로그래머스] 핸드폰 번호 가리기 / C++

[RedHat Linux 8] 리눅스 SSH 키 인증, 링크 생성

Comments powered by Disqus.