[프로그래머스] Level1. 문자열을 정수로 바꾸기

Benjamin·2023년 3월 3일
0

프로그래머스

목록 보기
34/58

내 풀이 1

class Solution {
    public int solution(String s) {
        int answer = 0;
        if(s.charAt(0) == '-') {
            s = s.substring(1,s.length());
            answer = -Integer.parseInt(s);
        }
        else answer= Integer.parseInt(s);
        return answer;
    }
}

'-'가 들어오면 NumberFormatException이 날까봐 -를 빼주고 숫자로 형변환 할 수 있도록 작성했다.

내 풀이 2

'-'가 숫자로 형변환할때 NumberFormatException이 날지안날지 궁금해져서 그냥 뭐가됐든 바꿔보는코드도 작성해봤다.

class Solution {
    public int solution(String s) {
        int answer = Integer.parseInt(s);
        return answer;
    }
}

배운 점

  • '-' 문자는 정수로 형변환했을 때 NumberFormatException이 나지않는다!!

0개의 댓글