본격적으로 LV2 에 들어가기전 2진수, 10진수 변환하는 함수를 연습했습니다
10진수값을 2진수로 변환하거나 2진수값을 10진수값으로 변환하는 코드를 짜보자
10진수 -> 2진수 변형

#include <string>
#include <vector>
#include <iostream>
#include <bitset>
using namespace std;
int solution(int n)
{
//10진수값 n이 주어졌을때 2진수값으로 변환시키는 함수
bitset<32> num(n);
string binary = num.to_string();
//앞의 0 제거
size_t temp = binary.find('1');
if (temp != string::npos)
{
binary = binary.substr(temp);
}
else
{
return 0;
}
int answer = stoi(binary);
return answer;
}
int main()
{
int a;
cout << "10진수값을 입력하세요: " << endl;
cin >> a;
int answer = solution(a);
cout << "변경된 2진수값은 " << answer << " 입니다" << endl;
return 0;
}
푸는방법 : bitset 을 사용하여 string값으로 변경하여 쉽게 풀수있다

2진수 -> 10진수 변형

#include <string>
#include <vector>
#include <iostream>
#include <bitset>
using namespace std;
int solution(string n)
{
int num = stoi(n, nullptr, 2);
return num;
}
int main()
{
string a;
cout << "2진수값을 입력하세요: " << endl;
cin >> a;
int answer = solution(a);
cout << "변현된 10진수값은 "<< answer << " 입니다" << endl;
return 0;
}
해당공식을 사용하면 쉽게 변형이 가능하다

