It Study/코딩테스트 연습

프로그래머스 lv1 - 문자열을 정수로 바꾸기

prlkt5200 2024. 9. 22. 16:37
반응형

class Solution {
    public int solution(String s) {
        int changeStr = 0;
        if(s.equals("0")){
        System.out.println("잘못된 값이 입력");
        }else{
        changeStr = Integer.parseInt(s);
        }
          return changeStr; 
    }
}

 

 

아래는 다른 사람의 풀이입니다.

이 분은 바로 Integer 클래스를 활용하는 것이 아닌 char 클래스를 활용하여 문자열을 탐색하는 과정으로 문자열을 정수로 바꾸는 것을 시도하였습니다. 이 분 풀이의 댓글에 어떤 분 말씀처럼 저도 생각없이 바로 라이브러리를 활용하게 된 것을 반성하게 되었습니다.

public class StrToInt {
    public int getStrToInt(String str) {
            boolean Sign = true;
            int result = 0;

      for (int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if (ch == '-')
                    Sign = false;
                else if(ch =='+')
                    result = result * 10 + (ch - '0');
            }
            return Sign?1:-1 * result;
    }
    //아래는 테스트로 출력해 보기 위한 코드입니다.
    public static void main(String args[]) {
        StrToInt strToInt = new StrToInt();
        System.out.println(strToInt.getStrToInt("-1234"));
    }
}
반응형