본문 바로가기
Computer/Algorithm_Java

[Algorithm_Java] 문자열 다루기 기본 (Success)

by HJ0216 2023. 10. 24.
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public boolean solution(String s) {
        boolean answer = true;
        
        if(!(s.length()==4 || s.length()==6)){
            answer = false;
            return answer;
        }
        
        for(int i=0; i<s.length(); i++){
            if(!Character.isDigit(s.charAt(i))){
                answer = false;
                return answer;               
            }
        }
        
        return answer;
    }
}
 
 

1. if(!(s.length()==4 || s.length()==6))

    - 길이 확인

2. if(!Character.isDigit(s.charAt(i)))

    - 숫자 확인

 

 

😮 다른 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
  }
}
 
 

* try-catch 활용

 

 

 

🔗 소스 코드
GitHub

 

📚 참고 자료

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr