[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
1. 아이디어
문자열에 들어 있는 숫자를 모두 더하는 문제다. 숫자는 모두 한 자리 자연수이고 연속된 숫자도 각각 따로 취급하므로, 숫자가 붙어 있어도 12가 아니라 1과 2로 더한다. 따라서 숫자 문자를 하나씩 정수로 바꿔 더하면 된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
class Solution {
public int solution(String my_string) {
int sum = 0;
for (char c : my_string.toCharArray()) {
if (Character.isDigit(c)) sum += c - '0';
}
return sum;
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
int solution(string my_string) {
int sum = 0;
for (char c : my_string) {
if (isdigit(c)) sum += c - '0';
}
return sum;
}
1
2
def solution(my_string):
return sum(int(c) for c in my_string if c.isdigit())
This post is licensed under CC BY 4.0 by the author.