gudii9
asked on
min concatination challenge
Hi,
I am trying below challenge
http://codingbat.com/prob/p105745
My code is like below.
i am failing all test cases. Please advise on how to modify and improve my code.
Thanks in advance.
I am trying below challenge
http://codingbat.com/prob/p105745
My code is like below.
public String minCat(String a, String b) {
int aLen=a.length();
int bLen=b.length();
if(aLen==bLen){
return a+b;
}
if(aLen>bLen){
return a+b;
}
if(aLen<bLen){
return a+b;
}
return null;
}
i am failing all test cases. Please advise on how to modify and improve my code.
Thanks in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
int minLen = Math.min(aLen, bLen);
return a.substring(Math.max(0, aLen-minLen)) + b.substring(Math.max(0, bLen-minLen));
is what I was talking about
Is the Math.max necessary?
Dunno for Java, but in most languages negative string positions result in errors.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
No :-\ Got you, we can and should omit the max.
int minLen = Math.min(aLen, bLen);
return a.substring(aLen-minLen) + b.substring(bLen-minLen);
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
i see instead of two if loops like i wrote now we can do in one return statement with substring as we already got minLen from Math.min function right?
please advise
please advise
You didn't have any loop. You used three IFs to catch all cases. That or the mathematical approach like shown by me are the common solutions.
right?Right! Instead of your two IFs.
Thanx 4 axxepting
ASKER
Open in new window
Like above?
Open in new window
Now i was able to pass all the tests. How can i improve my code.
Please advise