[프로그래머스/C++]Lv.0 - 유한소수 판별하기

YH J·2023년 4월 18일
0

프로그래머스

목록 보기
31/168

문제 링크

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

내 풀이

분모를 2나 5로 나눌 수 있을 때 까지 계속 나눈 뒤 해당 숫자로 a를 나누었을 때 나머지가 없으면 유한소수라고 판단해서 그렇게 코드를 짰다.

내 코드

#include <string>
#include <vector>

using namespace std;

int solution(int a, int b) {
    int answer = 0;
    
    while(b % 2 == 0 || b % 5 == 0)
    {
        if(b % 2 == 0)
            b /= 2;
        else if(b % 5 == 0)
            b /= 5;
    }
    if(a > b)
    {
        if(a % b == 0)
            answer = 1;
        else
            answer = 2;
    }
    else if(a < b)
    {
        if(b % a == 0)
            answer = 1;
        else 
            answer = 2;
    }
    else
        answer = 1;
    
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

int solution(int a, int b) {
    int answer = 0;
    while(b % 2 == 0)
    {
        b /= 2;
    }
    while(b % 5 == 0)
    {
        b /= 5;
    }
    return (a % b == 0)?1:2;
}

다른 사람의 풀이 해석

while을 2번해서 2랑 5를 제거한 뒤 삼항연산자로 코드 간결화

profile
게임 개발자 지망생

0개의 댓글