본문 바로가기
코딩테스트/LV. 0

LV. 0 :: 숨어있는 숫자의 덧셈

by KUROMI98 2023. 1. 25.

https://school.programmers.co.kr/learn/courses/30/lessons/120864

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

function solution(my_string) {
    var answer = 0;
    my_string = my_string.replaceAll(/[a-zA-Z]/g, "x");
    // 모든 알파벳을 전부 x로 바꿔준다. aAb1B2cC34oOp 을 xxx1x2xx34xxx 이런식으로
    var arr= my_string.split('x');
    // x로 나눠서 배열에 넣어준다 ["","","","1","2","","34","","",""] 이런식으로 
    
    for (i=0; i<arr.length; i++)
    { // answer에다가 arr의 원소 중 숫자인 원소들을 전부 더해 넣어준다.
        answer += Number(arr[i]);
    }
    return answer;
}

+230513

const solution = (my_string) => { 
    my_string = my_string.replaceAll(/[a-zA-Z]/g, " ");  
    return my_string.split(' ').map(x=>Number(x)).reduce((a, b) => a + b, 0);
}

230603 python

def solution(my_string):
    numbers = ""
    # my_string = "aAb1B2cC34oOp"
    
    for x in my_string:
        if x.isdigit(): numbers += x 
        else: numbers += 'x'
    # numbers = "xxx1x2xx34xxx"
    
    arr= numbers.split('x')
    # arr =  ["","","","1","2","","34","","",""]
    
    answer = 0
    
    for x in arr:
        if x.isdigit(): answer += int(x)
        
    return answer

230916 C++

#include <string>
#include <vector>

using namespace std;

int solution(string my_string) {
    int answer = 0;
    string temp = ""; // 숫자를 임시로 저장할 문자열

    for (char c : my_string) {
        if (isalpha(c)) {
            // 알파벳을 만나면 숫자를 더하고 temp 초기화
            if (!temp.empty()) {
                answer += stoi(temp);
                temp = "";
            }
        } else if (isdigit(c)) {
            // 숫자를 만나면 temp에 추가
            temp += c;
        }
    }

    // 마지막으로 남은 숫자를 처리
    if (!temp.empty()) {
        answer += stoi(temp);
    }

    return answer;
}

'코딩테스트 > LV. 0' 카테고리의 다른 글

LV. 0 :: 이진수 더하기  (0) 2023.01.26
LV. 0 :: 모스부호 (1)  (0) 2023.01.26
LV. 0 :: 컨트롤 제트  (0) 2023.01.24
LV. 0 :: OX퀴즈  (0) 2023.01.24
LV. 0 :: 문자열 계산하기  (0) 2023.01.24

댓글