Since I was solving problems in the Google Tech Dev Guide during the training, Make a note of what you think. Problem solved this time
When excerpting the problem statement
Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
And that. In summary, it says, "Take out only the numbers from the received string and add them." I think it's hard to understand if it's just sentences, It seems that the output should be as follows (implement the sumNumbers method)
sumNumbers("abc123xyz") → 123 sumNumbers("aa11b33") → 44 sumNumbers("7 11") → 18
As you can see from the ↑, If there are strings or spaces between the numbers, you need to add the respective numbers.
First, I identified the elements that might be included in the string.
Based on the above, we took the following approach this time.
The final code looks like this:
sample.java
class Test1{
public static void main(String args[]){
//For operation check
System.out.println(sumNumbers("abc123xyz"));
System.out.println(sumNumbers("aa11b33"));
System.out.println(sumNumbers("7 11"));
}
public static int sumNumbers(String str) {
// 1.Convert everything except numbers to half-width spaces
String buf = str.replaceAll("[^0-9]", " ");
// 2.Store in an array separated by spaces
String list[] = buf.split(" ");
int sum = 0;
// 3.Add all but empty elements in the array
for(int i = 0; i < list.length; i++){
if (!(list[i].isEmpty())){
sum = sum + Integer.parseInt(list[i]);
}
}
return sum;
}
}
If you have something like "I should do this more!", I would love to hear from you!
I usually write in Ruby, so I tried to solve it in Ruby as well.
sample.rb
def sumNumbers(str)
str.gsub(/[^0-9]/," ")
.split(" ")
.compact
.reject(&:empty?)
.sum{|v| v.to_i}
end
#For operation check
puts sumNumbers("abc123xyz")
puts sumNumbers("aa11b33")
puts sumNumbers("7 11")
With ruby, you can write using a method chain, so it's fun!
Recommended Posts