[Algorithm] Addition of digits

Problem description

Create a solution method that takes a natural number N, adds each digit of N, and returns. ** Example) If N = 123, return 1 + 2 + 3 = 6. ** **

conditions

--N range: Natural numbers less than 100,000,000

Input / output example

N answer
123 6
987 24

Commentary


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 in n to use the result of division by 10 for the next calculation.
        }

        return sum;
    }
}

Recommended Posts

[Algorithm] Addition of digits
Addition of guest login function
[Algorithm] Descending order of character strings
Number of digits in numeric item
[Rails] Addition of Ruby On Rails comment function
Rails Addition of easy and easy login function