본문 바로가기

프로그래머스

문자열 다루기 기본

728x90

나의코드

class Solution {
    public boolean solution(String s) {
        boolean answer = true;
        if(s.length() !=4 && s.length() !=6) return false;
        else
        {
            for(int i=0;i<s.length();i++)
            {
                if(s.charAt(i)<'0' || s.charAt(i)>'9')
                {
                    return false;
                }
            }
            
        }
        return true;
    }
}

 

베스트코드(프로그래머스 출처)

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;
  }
}

느낀점 : 자바의 문법을 많이 활용한 코드이다.

728x90

'프로그래머스' 카테고리의 다른 글

하샤드수  (0) 2022.12.26
없는숫자더하기  (0) 2022.12.21
두 정수 사이의 합  (0) 2022.12.19
x만큼 간격이 있는 n개의 숫자  (0) 2022.12.19
핸드폰번호가리기  (0) 2022.12.19