개발 공부

프로그래머스 문자열을 정수로 바꾸기 Java 본문

코딩 테스트

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

hyecozy 2022. 8. 7. 01:36

https://school.programmers.co.kr/learn/courses/30/lessons/12925

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

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

... 끝!

 

 

.

.

.

 

 

너무 간단해서 Integer.parseInt()를 안 쓰고 풀어보려고도 해봤다. 

근데 "1234"를 어떻게 한 글자 한 글자씩 빼내서 int형으로 바꿀 수 있는 건지 알 수 없었음..

각각의 숫자를 정수로 뽑으면 1 + 2 + 3 + 4 = 10 이렇게 나와버리지 않나?

자릿수 따져서 1 * 1000 + 2 * 100 + 3 * 10 + 4 이렇게 구해야 하나? .... Character에 또 좋은 기능이 없을까.. 하다가

그냥 짱나서 parseInt()의 내부를 들여다보기로 했다.

이 함수는 parseInt()를 안 쓰고 String을 int로 바꿨을 테니까. (당연함

 

그래서 보게 된 parseInt()의 내부

는 parseInt(s, radix)로 풀게 되어 있었기 때문에 parseInt(s, radix)의 내부

    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s, radix);
                }

                if (len == 1) { // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s, radix);
                }
                i++;
            }
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result -= digit;
            }
            return negative ? result : -result;
        } else {
            throw NumberFormatException.forInputString(s, radix);
        }
    }

결론은 "1234"를 이렇게 풀고 있었다.

1) "1"을 정수로 바꿔서 int형 변수 digit에 넣는다. //digit = 1

2) 변수 result에 10을 곱한다 // 0 * 10진수이므로, result = 0

3) result에 digit를 뺀다 //result = -1

4) "2"를 정수로 바꿔서 int형 변수 digit에 넣는다. //digit = 2

5) 변수 result에 10을 곱한다 // -1 * 10, result = -10

6) result에 digit를 뺀다 //result = -12 <<<<< 여기서부터 헐 소리 나옴... 이런 식으로 숫자를 채워나갈 수 있구나

7) "3"을 정수로 바꿔서 int형 변수 digit에 넣는다 //digit = 3

8) 변수 result에 10을 곱한다 // result = -120

9) result에서 digit를 뺀다 // result = -123

10) "4"를 정수로 바꿔서 digit에 넣는다 // digit = 4

11) result에 10을 곱한다 // result = -1230

12) result에서 digit를 뺀다 // result = -1234

13) negative가 false니까 -result를 반환

14)1234 나옴

각 자리의 숫자를 넣을 변수와, 진수만큼 곱해서 넣어둘 변수로 이렇게 뽑을 수 있다

나도 꼭 써먹어야지...

이런 수학적 사고 말고도 진수에 대한 것이나, int의 성질 등 예외 처리 보면서도 공부가 됐기 때문에 좋은 내부 탐색 시간이었다. int가 가질 수 있는 최대값과 최소값 같은 거는 정말 가볍게 훑고 지나간 것이었는데 이번 기회에 다시 짚고 넘어갈 수 있어서 유익했음.

cf) int 범위 

-2,147,483,648 ~ 2,147,483,647 (-2^31 ~ 2^31)

그래서 음수 처리해서 푼 것이군...

 

Comments