Contents

Adding digits (with.Java)

   Apr 19, 2024     2 min read

This is an article about the “digit addition (with.Java)” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

When an integer n is given as a parameter, complete the solution function to return the sum of each digit of n.

Restrictions

  • 0 ≤ n ≤ 1,000,000

Input/Output Example

nresult
123410
93021116

My solution to the problem

class Solution {
     public int solution(int n) {
         int answer = 0;
         String str = Integer.toString(n);
         for(int i = 0; i < str.length(); i++){
             int k = (int)str.charAt(i) - '0';
             answer += k;
         }
         return answer;
     }
}

Solution explanation

Method signature: public int solution(int n) This is a method that takes the integer n as a parameter and returns an integer value.

Initialize variable: int answer = 0; Initialize answer, the variable to store the result value, to 0.

Converting an integer to a string: String str = Integer.toString(n); Convert the input integer n to a string and store it in str.

Loop through the string and add the digits of each digit: for(int i = 0; i < str.length(); i++) Repeat for the length of the string.

int k = (int)str.charAt(i) - ‘0’; Get the ith character from the string, find the ASCII code value, subtract the ASCII code value of ‘0’, convert the result to an integer, and store it in k.

answer += k; Add the value k to the answer.

Return result value: return answer; Returns the value stored in the answer variable.

In this way, the code returns the value of adding each digit of the given integer.