프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

풀이 방법

10진수인 n을 k진수 문자열로 변환하고 해당 문자열을 조건에 맞춰 파싱 후 소수의 개수를 리턴하면 된다.

 

 

 

1. n을 k진수 문자열로 변환하여 문자열 arithmetic에 담는다.

2. 문자열을 조건에 맞춰 파싱하여 tmp에 담고 숫자로 변환 후 소수인지 판별하고 소수면 answer++

3. 반복문이 끝난 후 tmp가 비어있지 않다면 한 번 더 소수인지 판별하고 소수면 answer++

4. answer 리턴

#include <string>
#include <vector>

using namespace std;

bool isPrime(long long n) {
    if(n < 2) return false;
    for(long long i=2; i*i<=n; i++)
        if(!(n % i)) return false;
    
    return true;
}

int solution(int n, int k) {
    int answer = 0;
    string arithmetic = "";
    string tmp = "";
    
    while(n) {
        arithmetic += to_string(n % k);
        n /= k;
    }
    
    arithmetic = string(arithmetic.rbegin(), arithmetic.rend());
    
    for(int i = 0; i < arithmetic.length(); i++) {
        if(arithmetic[i] == '0' && !tmp.empty()) {
            long long num = stoll(tmp);
            if(isPrime(num)) answer++;
            tmp = "";
        }
        else tmp += arithmetic[i];
    }
    
    if(!tmp.empty()) {
        long long  n = stoll(tmp);
        if(isPrime(n)) answer++;
    }
    
    return answer;
}

'프로그래머스 > 2레벨' 카테고리의 다른 글

주차 요금 계산/C++  (0) 2023.01.20
땅따먹기/C++  (0) 2023.01.18
124 나라의 숫자/C++  (0) 2023.01.17
할인 행사/C++  (0) 2023.01.17
연속 부분 수열 합의 개수/C++  (0) 2023.01.17

+ Recent posts