How to implement condition strings (with.Java)
In this article, we learned about How to implement a condition string (with.Java)
Weβre going to learn by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it. Letβs start with the problem.
Problem
We want to compare the magnitude of two numbers based on a string, as follows.
If the two numbers are n and m β>β, β=β : n >= m β<β, β=β : n <= m β>β, β!β : n > m β<β, β!β : n < m Given two strings, ineq and eq. Complete the solution function so that, given two integers n and m, it returns 1 if n and m satisfy the conditions in ineq and eq, and 0 otherwise.
Example input and output
ineq: β<β eq: β=β n: 20 m: 50 result: 1
In other words, it returns 1 because 20 <= 50 is true.
My solution to the problem
class Solution {
public int solution(String ineq, String eq, int n, int m) {
int answer = 0;
if(ineq == "<"){
if(eq == "="){
answer = n <= m ? 1 : 0;
}else{
answer = n < m ? 1 : 0;
}
} else{
if(eq == "="){
answer = n >= m ? 1 : 0;
}else{
answer = n > m ? 1 : 0;
}
}
} return answer;
}
}
Solution Explanation
Weβve handled four possible cases by constructing logic to determine if the ineq string matches < and, if so, return a value based on whether it matches the eq character string =.
However, I noticed that it didnβt work for some cases. After further study, I realized why.
This β==β operator doesnβt work in some cases In JavaScript, I used to use the comparison operator for comparison, but it is said that Java recommends using the β.equals()β method rather than the β==β operator when comparing strings. The reason is to compare the actual contents of the strings when comparing strings.
The == operator compares references (memory addresses), so if two strings have the same content but are stored in different memory, they may not be equal. The .equals() method, on the other hand, compares the actual contents of the strings, so if the contents are the same, they are equal.
Therefore, a comparison like ineq == β<β might not work correctly even if the string contents are the same. In this case, using the .equals() method to compare string contents is the correct way to go.
My solution to the problem, which I solved again and passed
class Solution {
public int solution(String ineq, String eq, int n, int m) {
int answer = 0;
if(ineq.equals("<")){
if(eq.equals("=")){
answer = n <= m ? 1 : 0;
}else{
answer = n < m ? 1 : 0;
}
} else{
if(eq.equals("=")){
answer = n >= m ? 1 : 0;
}else{
answer = n > m ? 1 : 0;
}
}
} return answer;
}
}