Post

[Programmers] #181849 - 문자열 정수의 합 [Java][C++][Python]

[Programmers] #181849 - 문자열 정수의 합 [Java][C++][Python]

문제 링크


1. 아이디어

한 자리 정수로 이루어진 문자열 num_str에서 각 자릿수의 합을 반환하는 문제로 num_str의 각 문자를 순회하며 자릿수만 더하면 된다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(1)$

($N$ = num_str의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
class Solution {
    public int solution(String num_str) {
        int sum = 0;
        for (char c : num_str.toCharArray()) {
            sum += c - '0';
        }

        return sum;
    }
}
1
2
3
4
5
6
7
8
#include <bits/stdc++.h>
using namespace std;

int solution(string num_str) {
    int sum = 0;
    for (char c : num_str) sum += c - '0';
    return sum;
}
1
2
def solution(num_str):
    return sum(int(c) for c in num_str)

This post is licensed under CC BY 4.0 by the author.