코딩테스트/프로그래머스 - LV 0

[프로그래머스] 수학, 시뮬레이션, 문자열

웅드 2024. 1. 19. 15:27
  • 치킨 쿠폰
#include <string>
#include <vector>

using namespace std;

int solution(int chicken) {
    int answer = 0;
    int a=0;
    while(chicken >= 10){
        a = chicken % 10;
        chicken /=10;
        answer += chicken;
        chicken += a;
    }
    return answer;
}
  • 이진수 더하기
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

int exchange(string s){
    int a = 0; 
    reverse(s.begin(), s.end());
    for(int i=0; i<s.size(); i++){
        a += pow(2,i) * (s[i]-'0');
    }
    return a;
}

string solution(string bin1, string bin2) {
    string answer = "";
    if(bin1 == "0" && bin2 == "0") return "0";
    int a,b;
    a = exchange(bin1);
    b = exchange(bin2);
    int result;
    result = a+b;
    while(result != 0){
        if(result % 2 == 1) answer.push_back('1');
        else answer.push_back('0');
        result /= 2;
    }
    reverse(answer.begin(),answer.end());
    return answer;
}
  • A로 B만들기
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(string before, string after) {
    int answer = 0;
    sort(before.begin(), before.end());
    sort(after.begin(), after.end());
    for(int i=0; i< after.size(); i++){
        if(before[i] == after[i]){}
        else return 0;
    }
    return 1;
}
  • k의 개수
#include <string>
#include <vector>

using namespace std;

int solution(int i, int j, int k) {
    int answer = 0;
    
    for(int a=i; a <j+1; a++){
        int b = a;
        while(1){
            if(b==0) break;
            if(b%10 == k) answer++;
            b /=10;
        }
    }
    return answer;
}
반응형