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

반즈·2023년 12월 1일

프로그래머스 입문

목록 보기
24/51

문제 설명

문자열 my_string이 매개변수로 주어집니다. my_string안의 모든 자연수들의 합을 return하도록 solution 함수를 완성해주세요.

입출력 예


자바

나의 풀이

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        for(int num : arr){
            for(int i = 0; i < my_string.length(); i++){
                if(Integer.valueOf(my_string.charAt(i)) - 48 == num){
                    answer += num;
                }
            }
        } 
        return answer;
    }
}

참고 풀이 1 (.replaceAll(), .tocharArray(), getNumericValue())

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

        for(char ch : str.toCharArray()) {
            answer += Character.getNumericValue(ch);
        }

        return answer;
    }
}

참고 풀이 2 (.isDigit(), .charAt()+"")

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

        for(int i = 0; i < my_string.length(); i++)
        {
            if(Character.isDigit(my_string.charAt(i)))
                answer += Integer.parseInt(my_string.charAt(i)+"");
        }

        return answer;
    }
}

자바스크립트

나의 풀이 (정규식, 형변환)

function solution(my_string) {
    let answer = 0;
    let str = my_string.replaceAll(/[^0-9]/g,"").split('');
    for (let ch of str){
        answer += ch - 0;
    }
    return answer;
}

참고 풀이 1 (.reduce())

function solution(my_string) {
    const answer = my_string.replace(/[^0-9]/g, '')
                            .split('')
                            .reduce((acc, curr) => acc + Number(curr), 0);
    return answer;
}

참고 풀이 2 (.filter(), isNaN(), .reduce())

function solution(my_string) {
    return my_string.split("").filter((v)=> !isNaN(v)).reduce((a,b) => parseInt(a)+parseInt(b));
}

참고 풀이 3 (.match())

function solution(my_string) {
    return my_string.match(/[0-9]/g).reduce((a,b) => parseInt(a)+parseInt(b));
}
profile
나를 채우다

0개의 댓글