[JAVA] I tried to solve the problem of Google Tech Dev Guide

Introduction

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

problem

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.

I tried to solve it at once

First, I identified the elements that might be included in the string.

Based on the above, we took the following approach this time.

  1. Convert all non-numeric elements to blanks
  2. Store in an array separated by spaces
  3. Add all but empty elements in the array

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!

bonus

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

I tried to solve the problem of Google Tech Dev Guide
I tried to solve the problem of "multi-stage selection" with Ruby
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
I tried to solve the paiza campaign problem "Challenge from Kaito 813"
I tried to solve the Ruby karaoke machine problem (there is an example of the answer)
I tried to solve the Ruby bonus drink problem (there is an example of the answer)
[Java] I tried to solve Paiza's B rank problem
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
[Swift] I tried to implement the function of the vending machine
I tried to summarize the basic grammar of Ruby briefly
I tried to build the environment of WSL2 + Docker + VSCode
I tried to explain the method
I tried to build the environment of PlantUML Server with Docker
I tried to check the operation of gRPC server with grpcurl
I tried to summarize the methods of Java String and StringBuilder
I tried to solve AOJ's Binary Search
I tried to implement the Iterator pattern
I tried to summarize the key points of gRPC design and development
I tried to make full use of the CPU core in Ruby
I tried to visualize the access of Lambda → Athena with AWS X-Ray
I tried to measure and compare the speed of GraalVM with JMH
I tried to publish the reflex measurement application on the Google Play store
I tried to make a sample program using the problem of database specialist in Domain Driven Design
I want to output the day of the week
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to organize the session in Rails
I tried to chew C # (basic of encapsulation)
I want to var_dump the contents of the intent
I tried to set tomcat to run the Servlet.
[Java] Try to solve the Fizz Buzz problem
I tried using the profiler of IntelliJ IDEA
What I tried when I wanted to get all the fields of a bean
I tried to compare the infrastructure technology of engineers these days with cooking.
[Beginner] I tried to decorate the bar after displaying the details of the hamburger menu
I tried to organize the cases used in programming
I tried using the Server Push function of Servlet 4.0
I tried to check the operation of http request (Put) with Talented API Tester
I was addicted to the record of the associated model
I tried to create a log reproduction script at the time of apt install
I tried to decorate the simple calendar a little
I want to know the answer of the rock-paper-scissors app
I tried to solve AOJ's Small, Large, or Equal
I want to display the name of the poster of the comment
[WIP] I tried the configuration of Docker + Streama + NFS
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver
I tried to implement the Euclidean algorithm in Java
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
I didn't understand the topological sort, so I looked it up and implemented it in BFS, and then tried to solve the AtCoder problem.
I finished watching The Rose of Versailles, so I tried to reproduce the ending song in Java
I tried to make the sample application into a microservice according to the idea of the book "Microservice Architecture".
Since the reading of JdbcCodeList of TERASOLUNA is slow, I tried to register multiple at once.
I tried to touch the asset management application using the emulator of the distributed ledger Scalar DLT
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
I tried to develop the cache function of Application Container Cloud Service in the local environment
I tried to implement the like function by asynchronous communication
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to collect and solve Ruby's "class" related problems.
[JDBC] I tried to access the SQLite3 database from Java.