숨어있는 숫자의 덧셈(2)
문자열 my_string이 매개변수로 주어집니다. my_string은 소문자, 대문자, 자연수로만 구성되어있습니다. my_string안의 자연수들의 합을 return하도록 solution 함수를 완성해주세요.
my_string | result |
---|---|
"aAb1B2cC34oOp" | 37 |
"1a2b3c4d123Z" | 133 |
"aAb1B2cC34oOp"안의 자연수는 1, 2, 34 입니다. 따라서 1 + 2 + 34 = 37 을 return합니다.
"1a2b3c4d123Z"안의 자연수는 1, 2, 3, 4, 123 입니다. 따라서 1 + 2 + 3 + 4 + 123 = 133 을 return합니다.
function solution(my_string) {
let result = 0;
for(let i = 0; i < my_string.length; i++){
let tmp = 0; //초기화로 for문 안에서 진행
while(isNaN(Number(my_string[i]))=== false){
// 원소가 숫자라면 tmp 에 추가하라
tmp += my_string[i];
// console.log(tmp);
i++;
} //숫자가 연속되어 있다면 while문을 계속 반복함
result += Number(tmp);
// console.log(result);
}
return result;
}