[Programmers / JAVA] Level 1 Sum of Digits (12931)
[Programmers / JAVA] Level 1 Sum of Digits (12931)
Given a natural number N, create a solution function that finds the sum of each digit of N and returns it. For example, if N = 123, it should return 1 + 2 + 3 = 6.
@RWBwritten at 2021-12-18 09:31:11
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Given a natural number N, create a solution function that finds the sum of each digit of N and returns it. For example, if N = 123, it should return 1 + 2 + 3 = 6.
- Range of N: a natural number no greater than 100,000,000
| N | answer |
|---|---|
| 123 | 6 |
| 987 | 24 |
Input/Output Example #1
Same as the example in the problem description.
Input/Output Example #2
Since 9 + 8 + 7 = 24, it should return 24.
An algorithm that adds up all the digits of a number.
Convert the number to a string, split it into individual characters, and then convert each character back into a number and accumulate the values.
JAVA
/** * Sum of Digits class * * @author RWB * @since 2021.12.13 Mon 18:27:11 */ class Solution { /** * Method that returns the answer * * @param n: [int] natural number * * @return [int] answer */ public int solution(int n) { int answer = 0; String[] numbers = String.valueOf(n).split(""); for (String number : numbers) { answer += Integer.parseInt(number); } return answer; } }
# Programmers# Algorithm# JAVA# Level 1
