본문 바로가기

알고리즘 문제 풀이/Programmers

콜라츠 추측 - 1단계 (C, C++)

반응형
SMALL
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(long long num) {// long long으로 안하면 범위 넘어가서 이상한 답 뜸
    long long answer = 0;
    while (1) {
    	if (num == 1) break; // 먼저 확인 안하면 edge case로 1이 들어왔을 때 처리를 못한다.
        answer = answer + 1;
        if (num % 2 == 0) {
        	num = num / 2;
        }
        else {
        	num = (num * 3) + 1;
        }
        if (answer >= 500) {
        	answer = -1;
            break;
        }
    }
    return answer;
}

#include <vector>
#include <iostream>

using namespace std;

int solution(int num) {
	int answer = 0;
    while (1) {
    	if (num == 1) break;
        answer += 1;
        if (answer >= 500) {
        	answer = -1;
            break;
        }
        if (num % 2 == 0) num = num / 2;
        else if (num % 2 == 1) num = num * 3 + 1;
    }
    return answer;
}
반응형
LIST