Algorithm

[Conc & Sol] Integer.valueOf() vs Integer.parseInt()

Uykm 2024. 5. 16. 04:27

▼ What ? Why?

 1일 1알고리즘 스터디에서 이번에 해결한 "다트 게임"이라는 문제를 풀어봤는데, 문자열에서 특정 문자들을 추출하고, 추출한 문자에 따라 로직("점수", "보너스", "옵션")을 처리해 "다트 게임"에서 얻은 총점수를 구하는 문제였다. 문제를 해결하는 과정에서 `문자열(String)`을 `정수값(int)`로 변환해야 하는 경우가 있었는데, 문득 `Integer.valueOf()`와 `Integer.parseInt()' 사이에 어떤 차이가 있는지 궁금해져서 찾아보게 됐다.

 사실 두 메서드는 별다른 구분없이 정수형으로 변환해주는 메서드라고 생각하며 사용해왔다가, 이번에 두 메서드의 차이점이 은근 크다는 사실을 알게 되었다. 그래서 두 메서드의 차이점을 기억해둔다면, 나중에 개발을 할 때나 알고리즘 문제를 풀 때 유용하게 사용할 일이 있을 것 같아서 따로 정리해보았다.


Integer.parseInt() vs Integer.valueOf()

 

Integer.parseInt(String s)

  • 문자열을 `int` 기본형으로 변환하고, 반환된 값은 기본형 `int`이다.
    기본형 `int`가 필요한 경우에 사용하자 !
int number = Integer.parseInt("123");

 

Integer.valueOf(String s)

  • 문자열을 `Integer` 객체로 변환하고, 반환된 값은 `Integer` 객체이다.
    `Integer` 객체가 필요한 경우에 사용하고,컬렉션에 저장하거나 null 가능성을 처리해야 하는 경우에 사용하자 !
Integer number = Integer.valueOf("123");

 


▼ 알고리즘 문제 : "[1차] 다트 게임" 

 

[1차] 다트 게임

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

 

프로그래머스

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

programmers.co.kr

 

[ 나의 해결 코드 ]

import java.util.*;

class Solution {
    public int solution(String dartResult) {
        int totalScore = 0;
        int[] scores = new int[3];
        int index = 0;              // 현재 점수 인덱스
        
        int length = dartResult.length();
        int i = 0;
        
        while (i < length) {
            // 점수 계산
            StringBuilder scoreBuilder = new StringBuilder();
            while (i < length && Character.isDigit(dartResult.charAt(i))) { // 점수 추출
                scoreBuilder.append(dartResult.charAt(i));
                i++;
            }
            int score = Integer.parseInt(scoreBuilder.toString()); 
            // Integer.parseInt() : 기본형으로 반환
            // Integer.valueOf() : 참조형으로 반환
            
            // 보너스 계산
            char bonus = dartResult.charAt(i);
            i++;
            if (bonus == 'S') {
                score = (int) Math.pow(score, 1);
            } else if (bonus == 'D') {
                score = (int) Math.pow(score, 2);
            } else if (bonus == 'T') {
                score = (int) Math.pow(score, 3);
            }
            
            // 옵션 계산
            if (i < length && (dartResult.charAt(i) == '*' || dartResult.charAt(i) == '#')) {
                char option = dartResult.charAt(i);
                if (option == '*') {
                    score *= 2;
                    if (index > 0) {
                        scores[index - 1] *= 2;
                    }
                } else if (option == '#') {
                    score *= -1;
                }
                i++;
            }
            
            scores[index++] = score;
        }
        
        for (int s : scores) {
            totalScore += s;
        }
        
        return totalScore;
    }
}