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

han.user();·2023년 4월 4일
0

프로그래머스

목록 보기
34/87
post-thumbnail

class Solution {
    public int solution(String my_string) {
        int answer = 0;  // 결과값을 저장할 변수를 초기화합니다.
        String temp = "";  // 숫자를 임시로 저장할 변수를 초기화합니다.

        for (int i = 0; i < my_string.length(); i++) {  // 문자열을 순회합니다.
            char c = my_string.charAt(i);  // 현재 위치의 문자를 가져옵니다.
            if (Character.isDigit(c)) {  // 문자가 숫자인 경우
                temp += c;  // temp 변수에 숫자를 추가합니다.
            } else {  // 문자가 숫자가 아닌 경우
                if (!temp.equals("")) {  // temp 변수에 숫자가 저장되어 있는 경우
                   answer += Integer.parseInt(temp); // temp변수에 저장된 숫자를 결과값에 더함
                    temp = "";  // temp 변수를 초기화합니다.
                }
            }
        }
        if (!temp.equals("")) {  // 마지막으로 temp 변수에 숫자가 저장되어 있는지 확인합니다.
            answer += Integer.parseInt(temp);  // temp 변수에 저장된 숫자를 결과값에 더합니다.
        }
        if (answer == 0) {  // 결과값이 0인 경우
            return 0;  // 0을 반환합니다.
        }
        return answer;  // 결과값을 반환합니다.
    }
}
profile
I'm still hungry.

0개의 댓글