[Java] [Algorithm] Addition of digits

less than 1 minute read

Problem description

Create a solution method that receives a natural number N, adds each digit of N, and returns. **Example) When N=123, 1 + 2 + 3 = 6 is returned. **

Condition

  • Range of N: Natural number less than 100,000,000

I/O example

| N | answer | |:—————–|——————:| | 123| 6| | 987| 24|

Commentary

*The explanation is a code I created, so if you have a better algorithm, please share it!


public class Solution {
     public int solution(int n) {
         // for saving totals
         int sum = 0;
         while(n> 0) {
             sum += n %10; // Divide by 10 and add the remainder.
             n /= 10; // Substitute for n to use the result of dividing by 10 for the next calculation.
         }

         return sum;
     }
}