CODING/CS, 알고리즘, 자료구조 공부

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

codingTrip 2025. 6. 19. 08:31

나의 풀이

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

알고리즘이 아닌 함수를 사용했다.


 

다른 사람의 풀이

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

부호를 boolean 타입의 변수로 만드셨다.

for문을 통해 String 매개변수의 각 인덱스의 값을 결과 변수에 저장하셨다.

 

(ch - '0')는 문자를 숫자로 바꾸는 고전적인 방식이다.
예: '3' - '0' = 3

출처 : https://school.programmers.co.kr/learn/courses/30/lessons/12925/solution_groups?language=java