본문 바로가기
알고리즘 일기

프로그래머스 다음 큰 숫자 // 이진수 변환 // 시간초과됨(해결완료)

by Beijing_KingGod 2019. 9. 3.
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
vector<int> change(int n){
    vector<int> temp;
    while(n!=0){
        temp.push_back(n%2);
        n/=2;
    }
    return temp;
}
vector<int> add(vector<int> temp){
    temp[0]+=1;
    for(int i=0; i<temp.size()-1; i++){
        if(temp[i]==2){
            temp[i+1]+=1;
            temp[i]=0;
        }
    }
    if(temp[temp.size()-1]==2){
        temp.push_back(1);
        temp[temp.size()-2]=0;
    }
    return temp;
}
bool compare(vector<int> a, vector<int> b){
    int a_temp=0;
    int b_temp=0;
    for(int i=0; i<a.size(); i++){
        a_temp+=a[i];
    }
    for(int i=0; i<b.size(); i++){
        b_temp+=b[i];
    }
    return a_temp==b_temp;
}
int change_num(vector<int> temp){
    int n_temp=0;
    for(int i=0; i<temp.size(); i++){
        n_temp+=(temp[i]*pow(2,i));
    }
    return n_temp;
}
int solution(int n) {
    int answer = 0;
    vector <int> n_binary = change(n);
    vector <int> a_binary = add(n_binary);
    while(!compare(n_binary,a_binary)){
        a_binary=add(a_binary);
    }
    answer= change_num(a_binary);    
    return answer;
}

--> for 문으로 하나씩 검사 하고 벡터도 만드는 데 시간이 걸린다.

--> 그래서 벡터 만드는 것 생략 !! 1의 갯수 만 세기!!!!!!#########

#include <string>
#include <vector>
#include <iostream>
using namespace std;
int count(int num){
    int temp=0;
    while(num>0){
        if(num%2==1){
            temp++;
        }
        num/=2;
    }
    return temp;
}
int next_num(int num){
    int temp = count(num);
    while(temp != count(++num)){}
    return num;
}
int solution(int n) {
    int answer = next_num(n);
    return answer;
}

바로 통과 ////

'알고리즘 일기' 카테고리의 다른 글

피보나치 수열 // 동적 프로그래밍  (0) 2019.09.03
프로그래머스 땅따먹기 // get_max 함수 구현하기  (0) 2019.09.03
행렬 경우의수  (0) 2019.09.02
조합  (0) 2019.09.02
전체 순열  (0) 2019.09.02

댓글