관리 메뉴

bright jazz music

숫자 문자열과 영단어 본문

Algorithm

숫자 문자열과 영단어

bright jazz music 2022. 4. 13. 08:53

요구사항:

숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 
혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어진다.
s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성하라

 

class Solution {
    public int solution(String s) {
        String [] words = {"zero", "one", "two", "three", "four"
                            ,"five", "six", "seven"
                            ,"eight", "nine"};
        
        for(int i = 0 ; i < words.length; i++) {
            s = s.replace(words[i], String.valueOf(i));
        }
        //words배열의 인덱스에 대응하는 숫자값 i를 i로 대체할 것
        //반복문이 끝나면 s의 모든 영문자가 숫자로 바뀐다.
        
               
        return Integer.parseInt(s);
        //s를 인트로 바꿔서 반환 
        
    }
}

 

 

//보다 나은 풀이

class Solution {
    public int solution(String s) {
        String[] strArr = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        for(int i = 0; i < strArr.length; i++) {
            s = s.replaceAll(strArr[i], Integer.toString(i));
            //Integer.toString은 Number객체의 값을 String객체의 값으로 변환한다 
        }
        return Integer.parseInt(s);
    }
}

 

 

 

 

Integer.parseInt()

String 값을 정수 형태로 바꿔준다.

자세한 내용은 아래의 공식 문서를 확인할 것.

 

https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

 

Integer (Java Platform SE 8 )

Returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits. (Bits shifted out of the left hand, or high-order, side reenter on the right, or low-order.) Note that left r

docs.oracle.com

 

String.replace(oldChar, newChar)

oldChar를 newChar로 바꿔준다.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char-

 

String (Java Platform SE 8 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

String.valueOf()

배열에서 해당 값을 반환

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#valueOf-char:A-

 

String (Java Platform SE 8 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

Comments