Contents

Sum of String Integers (with.Java)

   Nov 8, 2023     1 min read

This is the “sum of string integers” problem.

We’re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem.

Problem

Complete the solution function so that, given a string num_str of single-digit integers, it returns the sum of each digit.

Example input and output
num_strresult
“123456789”45
“1000000”1

My solution to the problem

class Solution {
    public int solution(String num_str) {
        int answer = 0;
        for(int i = 0; i < num_str.length(); i++){
            answer += Integer.parseInt(String.valueOf(num_str.charAt(i)));
        }
    } return answer;
}
solution description

int answer = 0;: Initialize the variable answer to store the result. The initial value is 0.

for(int i = 0; i < num_str.length(); i++): Iterate over the input string num_str, checking each character.

num_str.charAt(i): Get the character located at the current index i.

String.valueOf(…): Converts a character to a string.

Integer.parseInt(…): Converts a string to an integer. Add the converted value to answer.

return answer;: Returns the result of adding all the numbers contained in the string.

This code adds all the numbers in the input string and returns the sum.

It iterates through the string character by character, converting each character to an integer, adding them together, and finally returning the sum of the additions.