[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
소문자, 대문자, 한 자리 숫자로 이루어진 문자열에서 숫자를 모두 더한 값을 구하는 문제.
[Programmers] #120851 - 숨어있는 숫자의 덧셈 (1) [Java][C++][Python]
1. 아이디어
문자열을 한 글자씩 훑어 숫자인 글자를 만나면 정수로 바꿔 누적 합에 더한다. 모든 숫자가 한 자리로만 주어지므로 인접한 숫자를 이어 붙여 여러 자리 수로 해석할 필요 없이 글자 단위로 처리하면 된다.
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.