[알고리즘 + 자료구조]/[프로그래머스]

프로그래머스 2개 이하로 다른 비트

Hevton 2023. 8. 10. 13:34
반응형

 

처음에는 숫자를 하나씩 늘려가며 찾는 방법을 생각했지만,

이게 숫자의 크기가 어마어마하다보니 + 1씩 하다가는 시간초과가 걸린다는 것을 알게 되었다

(00111111111111111 이런 수의 경우 ...)

 

 

그래서, 규칙을 찾아서 풀어야 한다는 점을 깨달았다.

그 규칙을 찾는게 어렵지만, 해봐야 아는 것이다.

 

진수가 가장 낮은 수부터, 0이 처음 등장할 때 해당 0을 1로 바꿔주고 그 이전 진수를 0으로 바꿔줘야 한다.

#include <string>
#include <vector>
#include <bitset>

using namespace std;

long long hello(long long n) {
    
    
    bitset<64> num(n);
    
    string s = num.to_string();
    
    long idx = s.rfind('0');
    
    s[idx] = '1';
    if(idx + 1 < 64)
        s[idx + 1] = '0';
    
    bitset<64> an(s);
    
    return an.to_ullong();
    
    
}

vector<long long> solution(vector<long long> numbers) {
    vector<long long> answer;
    
    
    for(auto num : numbers) {
        
        answer.push_back(hello(num));
        
        
    }
    
    return answer;
}
반응형