주니어 기초 코딩공부/JAVA_programmers_코딩테스트

숨어있는 숫자의 덧셈 (2)_programmers_lev00

jju_developer 2022. 12. 13. 21:42
728x90

<코딩 테스트>

문자열 my_string이 매개변수로 주어집니다. my_string은 소문자, 대문자, 자연수로만 구성되어있습니다. my_string안의 자연수들의 합을 return하도록 solution 함수를 완성해주세요.

 

<나의 풀이 과정>

우선 지난번 풀이하였던 숨어있는 숫자의 덧셈 (1) 과는 다르게 영어를 전부 [a-zA-Z] 으로 저거 하였으며, 여기서

중요한 점은 숫자가 하나씩 떨어지지 않게 하기 위해서 지우는 영문자를 "  " 공백을 두어 띄어서 제거하였습니다.

이때 split 메서드도 동일한 공백으로 나누어 주었습니다.

향상된 for 문을 이용하여 만약 "" 하나의 공백과 같지 않다면 answer에 숫자를 하나씩 더해주도록 Integer.parseInt를 사용하였습니다.

 

<나의 풀이 코드>

class Solution {
    public int solution(String my_string) {
		int answer = 0;
		String[] str = my_string.replaceAll("[a-zA-Z]", " ").split(" ");

		for (String s : str) {
			if (!s.equals("")) {
				answer += Integer.parseInt(s);
			}
		}
		return answer;
	}
}

 

<다른사람 풀이 1>

import java.util.StringTokenizer;

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        String s = my_string.replaceAll("[^0-9]", " ");
        StringTokenizer st = new StringTokenizer(s, " ");

        while (st.hasMoreTokens()) {
            answer += Integer.parseInt(st.nextToken());
        }

        return answer;
    }
}

<다른사람 풀이 2>

 

class Solution {
    public static int solution(String my_string) {
        int answer = 0;

        int idx = 0;
        while (idx < my_string.length()) {
            int charNum = my_string.charAt(idx);

            // 숫자로 시작하는 부분 탐색
            if (charNum >= (int) '0' && charNum <= (int) '9') {
                int len = 1;

                // 계속 해서 숫자가 나오는지 확인
                if (idx + len < my_string.length()) {
                    while (my_string.charAt(idx + len) >= (int) '0'
                            && my_string.charAt(idx + len) <= (int) '9') {
                        len++;
                        if (idx + len == my_string.length()) {
                            break;
                        }
                    }
                }

                // 숫자로 변환, 덧셈
                answer += Integer.parseInt(my_string.substring(idx, idx + len));

                idx += len;
            }

            if (idx == my_string.length() - 1) {
                return answer;
            }
            idx++;
        }

        return answer;
    }
}

 

 

 

 

 

 

 

 

 

 

728x90