문제
문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 a234이면 False를 리턴하고 1234라면 True를 리턴하면 됩니다.
(s는 길이 1 이상, 길이 8 이하인 문자열입니다.)
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean solution(String s) { | |
boolean answer = false; | |
int len = s.length(); | |
try { | |
if (len == 4 || len == 6) { | |
Integer.parseInt(s); | |
answer = true; | |
} | |
} catch (NumberFormatException e) { return answer; } | |
return answer; | |
} | |
} |
풀이
[Programmers] JavaScript에서 문자열 다루기 기본 (숫자로만 이루어진 문자열 체크하기)
문제 문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 a234이면 False를 리턴하고 1234라면 True를 리턴하면 됩니다. (s는 길이 1 이상, 길
uiyoji-journal.tistory.com
자바스크립트로 풀이할 때랑은 조금 다른 방식으로 풀었다.
문자열의 길이 체크는 동일하게 풀었지만, 형변환이 가능한지 여부로 boolean 값을 반환하도록 했다. 문자열 길이가 4 혹은 6일 때만 주어진 문자를 정수로 바꿔주는 Integer.parseInt 메서드를 실행한다. 형변환에 문제가 생긴다면 try 블록을 빠져나와 NumberFormatException 예외를 만날 것이다. 형변환이 문제 없이 이뤄진다면 answer 변수에 true를 할당한다.