본문 바로가기
Develop/백준 (Cpp)

[백준] 11104번 : Fridge of Your Dreams (C++)

by Tarra 2023. 2. 6.

11104번 : Fridge of Your Dreams


문제 )

Eirik drinks a lot of Bingo Cola to help him program faster, and over the years he has burned many unnecessary calories walking all the way to the kitchen to get some. To avoid this he has just bought a small fridge, which is beautifully placed next to his computer. To make it match his fancy big-tower with all its blinking LEDs, it is necessary to style it a bit.

He has bought a weight sensor with a display and a small general purpose programmable chip, to put underneath the fridge. The idea is to make the display show how many litres of Bingo Cola there is in the fridge. To do this he must read a binary register in the sensor, and convert it to a decimal number to be displayed.

 

 

입력 :

The first line of input gives n ≤ 1000, the number of test cases. Then follow n lines with positive numbers represented as 24-bit binary strings (0s and 1s).

 

 

출력 :

For each number, output its decimal representation, without any leading zeros.

 

 

 

 

풀이)

주어지는 2진수를 10진수로 바꾸면 되는 문제이다.

 

bitset을 이용하여 숫자로 바꾸고 싶었으나, 아직 잘 활용하지 못해

 

결국 일반적인 for문을 사용하여 각 이진수를 10진수로 변환하였다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <math.h>
#include <string>
 
using namespace std;
 
int main()
{
    int n;
    cin >> n;
 
    for (int i = 0; i < n; i++) {
        string bits;
        cin >> bits;
 
        int ans = 0;
        for (int j = 23; j > -1; j--) {
            if (bits[j] == '1') {
                ans += pow(223 - j);
            }
        }
        cout << ans << "\n";
    }
 
    return 0;
}
 
cs

 

메소드를 좀 더 찾아보니 
string STL의 stoi() 메소드에 2진수를 10진수로 표현할 수 있는 방법이 있었다.

 

stoi(string, position, int base)를 사용하면 2진수를 10진수로 간단히 변환이 가능하다.

 

따라서 위 코드는 다음과 같이 리팩토링이 가능하다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <math.h>
#include <string>
 
using namespace std;
 
int main()
{
    int n;
    cin >> n;
 
    for (int i = 0; i < n; i++) {
        string bits;
        cin >> bits;
        cout << stoi(bits, 02<< "\n";
    }
 
    return 0;
}
 
cs

출처 : https://www.acmicpc.net/problem/11104 

 

11104번: Fridge of Your Dreams

Eirik drinks a lot of Bingo Cola to help him program faster, and over the years he has burned many unnecessary calories walking all the way to the kitchen to get some. To avoid this he has just bought a small fridge, which is beautifully placed next to his

www.acmicpc.net