[C++] 백준 1193 : 분수찾기

Kim Nahyeong·2022년 1월 11일
0

백준

목록 보기
54/157

#include <iostream>
using namespace std;

int main() {
	int N;
	scanf("%d", &N);

	int i = 1;
	while (N > i) { // i 번째 대각선에 있다.
		N -= i;
		i++;
	}

	if (i % 2 != 0){
        cout << i + 1 - N << '/' << N << endl;
    } else {
        cout << N << '/' << i + 1 - N << endl;
    }
	
    return 0;
}

사실 원래 생각했던 코드는 이거다. 대각선의 규칙을 찾았지만, 몇번째를 출력하려고 한다면 배열에 넣어야할 것이라고 생각하여 메모리 초과가 발생하였다. 그냥 몇번째 대각선의 몇번째 수인 것만 파악하여 바로 출력하면 되었을텐데.

너무 어렵게 생각하는 경향이 큰 것 같다.
int string으로 출력도 그냥 cout을 사용하면 편하다.

처음 시도한 코드

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

int X, cnt = 1;
vector<string> v;

int main(int argc, char **argv){
    scanf("%d",&X);

    do{
        for(int i = 1; i <= X; i++){
            for(int j = 1; j <= i; j++){
                string str;
                if(i % 2 == 0){
                    str = to_string(j) + "/" + to_string(i-j+1); // int -> string
                } else {
                    str = to_string(i-j+1) + "/" + to_string(j); // int -> string
                }
                v.push_back(str);
                cnt++;
            }
        }
    } while(cnt < X);

    cout << v[X-1];

    return 0;
}

0개의 댓글