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

 

프로그래머스

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

programmers.co.kr

 

[C++][프로그래머스][Lv2] 12911. 다음 큰 숫자 

 


❗주의할 점 

: 10진수를 2진수로 바꾸는 방법을 알아야 풀 수 있는 문제였다.

: 얼마전에 비슷한 문제를 풀어서 푸는데 어려움은 없었다. 그리고 문제를 꼼꼼히 읽어야겠다는 생각을 했다....

 

사용한 함수

https://youcheachae.tistory.com/11

 

[C++][프로그래머스][Lv2] 70129. 이진 변환 반복하기

https://school.programmers.co.kr/learn/courses/30/lessons/70129 프로그래머스코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는

youcheachae.tistory.com

 


✅풀이방법 

#include <string>
#include <bitset>

using namespace std;

int solution(int _num) 
{
    int _idx = 1;
    int _answer = 0;

    // 기준이 되는 1의 갯수 
    int standartOneCnt = 0;
    // 2진수를 10진수로 변환 후, 문자열로 변환
    string numBinary = bitset<32>(_num).to_string();
    // 1로 시작하는 부분부터 끝까지 자르기
    string subNumBinary = numBinary.substr(numBinary.find('1'));

	// 기준이 되는 1의 갯수 구하기
    // algorithm 헤더의 count를 사용했으면 더 간편하게 가능함 
    for (int i = 0; i < subNumBinary.size(); i++)
    {
        if (subNumBinary[i] == '1')
            standartOneCnt++;
    }

    while (true)
    {
 	// 다음수 구하기 
        int _next = _num + _idx;

 	// 2진수 변환 후 1로 시작하는 부분~끝까지 자르기
        string _binary = bitset<32>(_next).to_string();
        string _subBinary = _binary.substr( _binary.find('1'));

	// 다음수의 1 구하기 
        int nextOneCount = 0;
        for (int i = 0; i < _subBinary.size(); i++)
        {
            if (_subBinary[i] == '1')
                nextOneCount++;	
        }

	// 문제조건 n과 n다음수를 2진수로 변환했을 때 1갯수가 같으면
        if (standartOneCnt == nextOneCount)
        {
            _answer = _next;
            break;
        }
        
        _idx++;
    }

    return _answer;
}

 


https://github.com/kimYouChae/C-Programmers

 

GitHub - kimYouChae/C-Programmers

Contribute to kimYouChae/C-Programmers development by creating an account on GitHub.

github.com

 

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

 

프로그래머스

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

programmers.co.kr

 

[C++][프로그래머스][Lv2] 70129. 이진 변환 반복하기 

 


❗주의할점 (1)

: 10진수를 2진수로 바꾸는 방법을 알아야 풀 수 있는 문제였다.

 

✅ #include <bitset>bitset< 생성할 bit 수 >(2진수로 변환할 수

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
	int num = 150000;

	string str = bitset<32>(num).to_string();
	// 0000 0000 0000 0000 0000 0000 0000 0000 생성

	string temp = "";
	cout << str << endl;
      // 00000000000000100100100111110000 출력 

	for (int i = 0; i < str.size(); i += 4) {
		string temp = str.substr(i, 4);
		cout << temp << " ";
	}
      // 0000 0000 0000 0010 0100 1001 1111 0000 출력
    
}

출력화면

 

: 문제에서 표기한 최댓값 150,000을 2진수로 변경해보았다.

: int 는 4바이트, 즉 32비트이다.  32비트안에 다 표현할 수 있다.

 ▶️32비트를 사용하면 문제조건에 맞게 2진수로 변경할 수 있다.

2,147,483,647 를 2진수로 표현

 

➕만약 bit수가 모자르면 어떻게 되는거지 ?

	int num = 150000;

	string str = bitset<6>(num).to_string();
        // 32비트 -> 6비트로 변경

: 32비트를 6비트로 바꾸어 출력해보았다.

출력화면

: 오류가 뜰 꺼라 예상했지만, 생성한 비트수 만큼만 출력한다.

 

❗주의할점 (2)

: 10진수를 2진수로 변환 후, string으로 변환하는데 1이 나오기 전 0 은 0갯수를 카운트 할 때 들어가면 안된다.

	int num = 17;

	string str = bitset<32>(num).to_string();
	// 0000 0000 0000 0000 0000 0000 0000 0000 생성

	string temp = "";
	cout << str << endl;;

 

출력화면

: 예를들어 17을 2진수로 바꾸었을 때

00000000000000000000000000010001 :  0개수 30개 , 1개수 2개 ❌

 

<string>헤더의 substr()과 find()

int num = 17;

string str = bitset<32>(num).to_string();
// 0000 0000 0000 0000 0000 0000 0000 0000 생성

string answer = str.substr(str.find('1'));
cout << answer << endl;

출력화면

: 예를들어 17을 2진수로 바꾸었을 때

10001 : 0개수 3개, 1개수 2개 ⭕

 

: str.find(char c) : 문자열에서 char이 처음으로 나온 인덱스(type : int)를 반환한다.

: str.substr(int i) : 문자열에서 인덱스에서 시작해서, 맨 끝 까지 자른 string을 반환한다.

 

<algorithm>헤더의 count(string의 시작 iterator , string의 끝 iterator , '찾을 문자 char ')

	int myCount = count(str.begin(), str.end(), '1');
	cout << myCount;

: 문자열안에서 해당 char 형 문자가 몇개 들어있는지, 갯수 (type : int)를 return 한다


✅ 풀이방법

#include <iostream>
using namespace std;
#include <string>
#include <algorithm>
#include <vector>
#include <bitset>

vector<int> solution(string str) {
    vector<int> answer;
    
    string temp = str;
    int wholeZero = 0;
    int progress = 0;
    while ( true )
    {
        if (temp == "1")
            break;

        progress++;
        int zero = count(temp.begin() , temp.end(), '0');
        int remain = temp.length() - zero;

        wholeZero += zero;

        // remian을 2진수로 (int형 변수를 2진수로 / int는 4바이트 32비트)
        string binaryStr = bitset<32>(remain).to_string();

        // binaryStr은 0000... 처럼 0 부터 시작할 수 도 있으니 자르기
        // string 의 find (1의 위치 찾음) , 시작 1부터 끝까지 자르기 
        string substrBinary = binaryStr.substr( binaryStr.find('1'));

        temp = substrBinary;
    }
    

    answer.push_back(progress);
    answer.push_back(wholeZero);
    return answer;
}

 


https://github.com/kimYouChae/C-Programmers

 

GitHub - kimYouChae/C-Programmers

Contribute to kimYouChae/C-Programmers development by creating an account on GitHub.

github.com

 

+ Recent posts