18. Exceptional Server
[ 난이도: Medium | 분야: Classes ]
1. 과제
이번 과제에서는, 복잡한 계산을 하는 작은 연산 서버가 동작하는동안 발생하는 에러 메시지들을 다루어야 한다.
2개의 큰 숫자를 입력으로 받고 대수 연산 결과를 반환하는 함수가 있다.
안타깝게도, 연산하는동안 발생할 수 있는 다양한 에러들이 있다.
문제가 발생했을 때 적절한 에러 메시지를 출력할 수 있는 코드를 완성하라.
이 함수의 동작은 아래와 같다:
- 만약 연산 함수가 주어진 인자들로 안정적으로 동작한다면, function call의 결과를 출력해라.
- 만약 연산에 필요한 만큼의 메모리를 할당 받지 못한다면, Not enough memory.를 출력해라.
- 만약 다른 표준 C++ 예외가 발생한다면, Exception: S를 출력해라.
(여기서 S는 예외의 에러 메시지이다.)
- 만약 비표준 에러가 발생한다면, Other Exception.을 출력해라.
입력 형식
첫 번째 줄에는 테스트 케이스의 개수인 정수 T를 포함한다.
각 T 하위 시퀀스들은 2개의 공백으로 분리된 정수인 A와 B를 포함한다.
제약 사항
T는 1보다 크거나 같고 10^3보다 작거나 같다.
A, B는 0보다 크거나 같고 2^60보다 작거나 같다.
출력 형식
각 테스트 케이스별로, 단일 줄로 위의 함수 동작에 맞게 출력해라.
모든 메시지가 출력된 후 잠겨있는 stub 코드가 서버의 로드를 출력한다.
입력 예시
2
-8 5
1435434255433 5
출력 예시
Exception: A is negative
Not enough memory
2
설명
-8은 음수이기에 'Exception: A is negative'를 던진다. 두 번째 입력은 너무 크기 때문에 'not enough memory'를 출력한다.
2는 서버의 로드를 의미한다.
문제
#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;
class Server {
private:
static int load;
public:
static int compute(long long A, long long B) {
load += 1;
if(A < 0) {
throw std::invalid_argument("A is negative");
}
vector<int> v(A, 0);
int real = -1, cmplx = sqrt(-1);
if(B == 0) throw 0;
real = (A/B)*real;
int ans = v.at(B);
return real + A - B*ans;
}
static int getLoad() {
return load;
}
};
int Server::load = 0;
int main() {
int T; cin >> T;
while(T--) {
long long A, B;
cin >> A >> B;
/* Enter your code here. */
}
cout << Server::getLoad() << endl;
return 0;
}
정답
#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;
class Server {
private:
static int load;
public:
static int compute(long long A, long long B) {
load += 1;
if(A < 0) {
throw std::invalid_argument("A is negative");
}
vector<int> v(A, 0);
int real = -1, cmplx = sqrt(-1);
if(B == 0) throw 0;
real = (A/B)*real;
int ans = v.at(B);
return real + A - B*ans;
}
static int getLoad() {
return load;
}
};
int Server::load = 0;
int main() {
int T; cin >> T;
while(T--) {
long long A, B;
cin >> A >> B;
/* Enter your code here. */
try{
cout << Server::compute(A, B) << endl;
}
catch(const bad_alloc& e) {
cout << "Not enough memory" << endl;
}
catch(const exception& e) {
cout << "Exception: " << e.what() << endl;
}
catch(int e) {
cout << "Other Exception" << endl;
}
}
cout << Server::getLoad() << endl;
return 0;
}
©️ Hackerrank. All Rights Reserved
'프로그래밍 언어 > C, C++' 카테고리의 다른 글
[Hackerrank] 20. Abstract Classes - Polymorphism (0) | 2024.02.17 |
---|---|
[Hackerrank] 19. Virtual Functions (0) | 2024.02.16 |
[Hackerrank] 17. Inherited Code (0) | 2024.02.14 |
[Hackerrank] 16. Box It! (0) | 2024.02.13 |
[Hackerrank] 15. Classes and Objects (2) | 2024.02.09 |