본문 바로가기

프로그래밍 언어/C, C++

[Hackerrank] 17. Inherited Code

17. Inherited Code

[ 난이도: Medium | 분야: Classes ]

1. 과제

과제 설명

회사 웹사이트에서 사용자 이름을 사용할 수 있는지 확인하는 코드 조각을 상속하려고 한다.

이 함수는 잘 동작하지만, 사용자 이름이 너무 짧으면 예외(exception)를 발생한다.

코드를 분석하면서, 아무도 예외 처리를 하지 않았다는 것을 알게 되었다.

상속 코드는 에디터에서 잠금 영역에서 제공되어 있다.

예외 처리가 가능하도록 코드를 작성하고, 예외가 발생할 경우, Too short: n(n은 사용자가 입력한 사용자 이름의 길이이다.)을 출력하라.

입력 형식

첫 번째 줄은 테스트 케이스의 개수인 정수 t를 포함한다.

각 t개의 하위 시퀀스 줄들은 단일 사용자 이름 문자열, u로 테스트 케이스를 표시하고 있다.

제약 사항

t는 1보다 크거나 같고 1000보다 작거나 같다.

u의 절댓값은 1보다 크거나 같고 100보다 작거나 같다.

사용자 이름은 오직 대문자와 소문자만 포함하고 있다.

출력 형식

stdout으로 직접 출력하지 마라. 만약 직접 짠 코드가 올바르게 동작한다면, 잠겨있는 stub 코드가 알아서 유효하다면 Valid를, 유효하지 않다면 Invalid를 또는 사용자 이름이 너무 짧으면 Too short: n를 각 테스트 케이스마다 개별 줄로 출력한다.

입력 예시

3
Peter
Me
Arxwwz

출력 예시

Valid
Too short: 2
Invalid

설명

사용자 이름 Me는 2개의 문자로만 구성되기에 너무 짧다. 그렇기에 Too short: 2를 출력하게 된다.

모두 다른 유효성 검사는 에디터의 잠긴 코드에 의해 다루어진다.

문제

#include <iostream>
#include <string>
#include <sstream>
#include <exception>
using namespace std;

/* Define the exception here */


bool checkUsername(string username) {
	bool isValid = true;
	int n = username.length();
	if(n < 5) {
		throw BadLengthException(n);
	}
	for(int i = 0; i < n-1; i++) {
		if(username[i] == 'w' && username[i+1] == 'w') {
			isValid = false;
		}
	}
	return isValid;
}

int main() {
	int T; cin >> T;
	while(T--) {
		string username;
		cin >> username;
		try {
			bool isValid = checkUsername(username);
			if(isValid) {
				cout << "Valid" << '\n';
			} else {
				cout << "Invalid" << '\n';
			}
		} catch (BadLengthException e) {
			cout << "Too short: " << e.what() << '\n';
		}
	}
	return 0;
}
더보기

정답

#include <iostream>
#include <string>
#include <sstream>
#include <exception>
using namespace std;

/* Define the exception here */
class BadLengthException : public exception
{
    private:
        string myLength;
    public:
        BadLengthException(int n) {
            myLength = (char)(n+48);
        }
        
        virtual const char * what() const throw()
        {
            return myLength.c_str();
        }
};

bool checkUsername(string username) {
	bool isValid = true;
	int n = username.length();
	if(n < 5) {
		throw BadLengthException(n);
	}
	for(int i = 0; i < n-1; i++) {
		if(username[i] == 'w' && username[i+1] == 'w') {
			isValid = false;
		}
	}
	return isValid;
}

int main() {
	int T; cin >> T;
	while(T--) {
		string username;
		cin >> username;
		try {
			bool isValid = checkUsername(username);
			if(isValid) {
				cout << "Valid" << '\n';
			} else {
				cout << "Invalid" << '\n';
			}
		} catch (BadLengthException e) {
			cout << "Too short: " << e.what() << '\n';
		}
	}
	return 0;
}

 

 

 

 

 

©️Hackerrank. All Rights Reserved

'프로그래밍 언어 > C, C++' 카테고리의 다른 글

[Hackerrank] 19. Virtual Functions  (0) 2024.02.16
[Hackerrank] 18. Exceptional Server  (2) 2024.02.14
[Hackerrank] 16. Box It!  (0) 2024.02.13
[Hackerrank] 15. Classes and Objects  (2) 2024.02.09
[Hackerrank] 14. Classes  (0) 2024.02.09