https://school.programmers.co.kr/learn/courses/30/lessons/12918?language=java
1. 본인 풀이
- 길이가 4나 6이 아니면 바로 리턴
- for문 돌며 숫자가 아니면 바로 리턴
- 리턴이 안되면 결국 true
class Solution {
public boolean solution(String s) {
if(s.length() != 4 && s.length() != 6) return false;
for(int i = 0; i<s.length() ; i++){
char c = s.charAt(i);
if(c >= '0' && c <= '9');
else return false;
}
return true;
}
}
2. 예외처리 활용
- 길이가 4나 6인 것 중 int로 변환이 가능하면 문자가 없다는 뜻이므로 true, 변환불가능하면 문자가 있다는 뜻이므로 false
- 기발한 생각이지만 자바 특정 버전 이후로는 -123, +123도 모두 숫자로 변환해주기 때문에 이 코드는 사용하지는 못하는 코드입니다.
class Solution {
public boolean solution(String s) {
if(s.length() == 4 || s.length() == 6){
try{
int x = Integer.parseInt(s);
return true;
} catch(NumberFormatException e){
return false;
}
}
else return false;
}
}
3. 정규표현식 활용
- matches함수에 정규표현식을 결합해서 0-9 사이이면 true
import java.util.*;
class Solution {
public boolean solution(String s) {
if (s.length() == 4 || s.length() == 6) return s.matches("(^[0-9]*$)");
return false;
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 3진법 뒤집기 / 진법 변환 (0) | 2025.02.26 |
---|---|
[프로그래머스] 같은 숫자는 싫어 (0) | 2025.02.25 |
[프로그래머스] 나누어 떨어지는 숫자 배열 (0) | 2025.02.20 |
[프로그래머스] 정수 제곱근 판별 (0) | 2025.02.20 |
[프로그래머스] 정수 내림차순으로 배치하기 (0) | 2025.02.20 |