-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumDigit.java
More file actions
38 lines (36 loc) · 928 Bytes
/
Copy pathNumDigit.java
File metadata and controls
38 lines (36 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package level1;
/*
* 자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
제한사항
N의 범위 : 100,000,000 이하의 자연수
입출력 예
N answer
123 6
987 24
입출력 예 설명
입출력 예 #1
문제의 예시와 같습니다.
입출력 예 #2
9 + 8 + 7 = 24이므로 24를 return 하면 됩니다.
*/
public class NumDigit {
public static void main(String[] args) {
SolutionNumDigit su = new SolutionNumDigit();
int n = 123;
// int n = 987;
System.out.println(su.solution(n));
}
}
class SolutionNumDigit {
public int solution(int n) {
int answer = 0;
String s = "" + n;
char[] c = new char[s.length()];
for(int i=0; i<s.length(); i++) {
c[i] = s.charAt(i);
answer += c[i] - '0';
}
return answer;
}
}