Contents

Addition of hidden numbers 2 (with.Java)

   May 7, 2024     2 min read

This is an article about the problem “Addition of hidden numbers 2 (with.Java)”.

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

The string my_string is given as a parameter.

my_string consists only of lowercase letters, uppercase letters, and natural numbers.

Complete the solution function to return the sum of the natural numbers in my_string.

Restrictions

  • 1 ≤ length of my_string ≤ 1,000
  • 1 ≤ natural number in my_string ≤ 1000
  • Consecutive numbers are considered one number.
  • There is no case where there is a leading 0, such as 000123.
  • If there are no natural numbers in the string, please return 0.

Input/Output Example

my_stringresult
“aAb1B2cC34oOp”37
“1a2b3c4d123Z”133

My solution to the problem

class Solution {
 public int solution(String my_string) {
 int answer = 0;
 String[] strArr = my_string.replaceAll("[a-zA-Z]", " ").split(" ");

 for(String str : strArr){
 if(!str.equals("")){
 answer += Integer.valueOf(str);
 }
 }
 return answer;
 }
}

Solution explanation

  • Alphabet substitution and string separation: Replaces the alphabet with spaces in a given string, separates the results based on spaces, and creates a string array.
  • Number extraction and summation: Iterate through the string array, convert each element to a number, and sum the converted numbers. Empty strings are ignored.
  • Return result: Returns the summed result.

Code pros and cons

  • Pro: Used regular expressions to replace alphabets with spaces and easily split strings. The code is written to be concise and easy to understand.
  • Disadvantage: This code assumes that the input fits the given format. Exception handling is required when malformed input is given. In the process of separating and summing strings, additional string arrays are created, which uses more memory.