개요
백준 문제 1373번을 풀면서 어려웠던 점과 코드를 정리한다.
소요 시간 : 10분
https://www.acmicpc.net/problem/1373
문제
2진수가 주어졌을 때, 8진수로 변환하는 프로그램을 작성하시오.
코드
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <iostream> #include <stack> using namespace std;
void solve() { string binary; int countThree = 0; int digit = 1; int result = 0; cin >> binary; stack<int> s; for(int i=binary.size()-1;i>=0;--i) { result += (binary[i] - '0') * digit; countThree++; digit*=2; if(countThree == 3) { s.push(result % 8); countThree = 0; result = 0; digit = 1; } } if(countThree != 0) { s.push(result % 8); } while(s.size()!= 0) { cout << s.top(); s.pop(); }
}
int main() { ios_base :: sync_with_stdio(0); cin.tie(0); solve(); }
|
풀이
2진수 입력 -> 맨끝에서 부터 3개씩 카운트하며 결과값을 스택에 저장
카운트가 3개가 되지 않은 경우 -> 정확히 떨어지지 않은 경우이므로 예외로 결과값 저장
저장된 스택에서 값 출력 = 정답
배울 점, 메모
설계,문제 풀이법을 오래 생각할 수록 코드 작성은 간결해진다.
물론 코드를 작성하는중에만 생각나는 것들도 있기는 하다.