blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-18 09:31:11
Programmers

시리즈 모아보기

Programmers

51 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Sum of Digits

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
Nanswer
1236
98724

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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08