Algorithm

스트링을 숫자로 바꾸기 (String to Integer)

OOOooOOoo·2018년 4월 23일·조회 5,640

1. 문제

출처 : https://programmers.co.kr/learn/challenge_codes/112

strToInt 메소드는 String형 str을 매개변수로 받습니다. str을 숫자로 변환한 결과를 반환하도록 strToInt를 완성하세요.예를들어 str이 1234이면 1234를 반환

하고, -1234이면 -1234를 반환하면 됩니다. str은 부호(+,-)와 숫자로만 구성되어 있고, 잘못된 값이 입력되는 경우는 없습니다.


2. 코드

public class StrToInt {
    public int getStrToInt(String str) {
    	try {
    		return Integer.parseInt(str);
    	} catch(Exception e) {
    		return 0;
    	}
    }

    public static void main(String args[]) {
        StrToInt strToInt = new StrToInt();
        System.out.println(strToInt.getStrToInt("-1234"));
    }
}

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.