BEAKJOON
백준(1193번 분수찾기)풀이 C++
Shin_jisoo
2021. 1. 12. 18:04
728x90
1193번: 분수찾기
첫째 줄에 X(1 ≤ X ≤ 10,000,000)가 주어진다.
www.acmicpc.net
표를
1/1
1/2 2/1
3/1 2/2 1/3
1/4 2/3 3/2 4/1
▪▪▪
로 생각했을 때
1) 주석 없는 VERSION
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
int x;
cin >> x;
int top = 0;
int bottom = 0;
int cnt = 1;
while (cnt<x) {
x = x - cnt;
cnt++;
if (x < cnt) break;
}
if (cnt % 2 == 0) {
for (int i = cnt;i > 0;i--) {
top++;
bottom = i;
x--;
if (x == 0) {
break;
}
}
}
else {
for (int i = cnt;i > 0;i--) {
bottom++;
top = i;
x--;
if (x == 0) {
break;
}
}
}
cout << top << "/" << bottom;
}
2) 주석 있는 VERSION
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
int x;
cin >> x; // 입력 받을 변수
int top = 0; // 분자
int bottom = 0; // 분모
int cnt = 1; // 몇 번째 줄인지
//입력 받은 변수가 몇 번째 줄에 있는지 검사
while (cnt<x) {
x = x - cnt;
cnt++;
if (x < cnt) break;
}
// 짝수인 경우 분자는 1씩 증가
// 분모는 cnt부터 1씩 감소
if (cnt % 2 == 0) {
for (int i = cnt;i > 0;i--) {
top++;
bottom = i;
x--;
if (x == 0) {
break;
}
}
}
// 홀수인 경우 분자는 cnt부터 1씩 감소
// 분모는 1씩 증가
else {
for (int i = cnt;i > 0;i--) {
bottom++;
top = i;
x--;
if (x == 0) {
break;
}
}
}
cout << top << "/" << bottom;
}