Addition of hidden numbers 1 (with.Java)
This is an article about the “Addition of hidden numbers 1” 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
The string my_string is given as a parameter.
Complete the solution function to return the sum of all natural numbers in my_string.
Restrictions
- 1 ≤ length of my_string ≤ 1,000
- my_string consists only of lowercase letters, uppercase letters, and one-digit natural numbers.
Input/Output Example
my_string | result |
---|---|
“aAb1B2cC34oOp” | 10 |
“1a2b3c4d123” | 16 |
My solution to the problem
class Solution {
public int solution(String my_string) {
int answer = 0;
for (char ch : my_string.toCharArray()) {
if (Character.isDigit(ch)) {
answer += Character.getNumericValue(ch);
}
}
return answer;
}
}
Solution explanation
- solution(String my_string): Extracts a number from the given string my_string and returns the result of adding the extracted numbers.
- int answer: Variable to store the final result.
- While iterating through the string, use Character.isDigit(ch) to check whether each character is a number. If it is a number, use Character.getNumericValue(ch) to accumulate and add the numbers.
- Returns the final added value.
Code Advantages
- Easy to add numbers: The process of extracting numbers from each letter and adding them is simple and intuitive.
Code Disadvantages
- Number range limitation: The code extracts only numbers from 0 to 9 from the string and adds them. If you need a different number range, you will need to modify your code.