Convert a string to an integer (with.Java)
This is a recap of the āConvert a string to an integerā problem.
Weāre going to learn by solving coding test questions, reflecting on the problems we solved, and exploring other ways to solve them.
Letās start with the problem
Problem
Complete the solution function so that, given a string n_str consisting of only numbers, it converts n_str to an integer and returns it.
Example input and output
n_str | result |
---|---|
ā10ā | 10 |
ā8542ā | 8542 |
My solution to the problem
class Solution {
public int solution(String n_str) {
int answer = Integer.parseInt(n_str);
return answer;
}
}
Explanation of the solution
The Integer.parseInt() function was used to return a string as an integer.