프로그래머스

[코딩테스트 연습] 영어가 싫어요 - Lv.0

yujin0517 2023. 5. 6. 15:50

문제: 영어가 싫어요

 

<코드>

class Solution {
    public long solution(String numbers) {
        long answer = 0;
        
        numbers = numbers.replaceAll("one", "1")
            .replaceAll("two", "2")
            .replaceAll("three", "3")
            .replaceAll("four", "4")
            .replaceAll("five", "5")
            .replaceAll("six", "6")
            .replaceAll("seven", "7")
            .replaceAll("eight", "8")
            .replaceAll("nine", "9")
            .replaceAll("zero", "0");
        
        answer = Long.parseLong(numbers);
        return answer;
    }
}

 

<문제 풀이>

numbers 문자열에 있는 모든 영어 단어를 해당 숫자로 변환하여 저장한다. 

return 값은 Long 형이기 때문에 Long.parseLong()으로 형변환을 한 뒤 answer에 저장한다. 

replaceAll() 메서드를 사용하면 문자열에 있는 해당 문자를 모두 변환하고 싶은 문자로 변환해 준다.