[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
1. 아이디어
주어진 문자열 my_string을 한 글자씩 훑어 숫자인 글자를 만나면 정수로 바꿔 누적해서 더하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(1)$ |
($N$ = my_string의 길이)
3. 코드
풀이 [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.