gudii9
asked on
sameFirstLast
hi,
I am trying below challenge
http://codingbat.com/prob/p118976
i am failing in one test case
please advise
I am trying below challenge
http://codingbat.com/prob/p118976
i am failing in one test case
public boolean sameFirstLast(int[] nums) {
int numsLen=nums.length;
int first=nums[0];
int last=nums[numsLen-1];
if(numsLen>=1&&first==last)
return true;
return false;
}
Expected Run
sameFirstLast({1, 2, 3}) → false false OK
sameFirstLast({1, 2, 3, 1}) → true true OK
sameFirstLast({1, 2, 1}) → true true OK
sameFirstLast({7}) → true true OK
sameFirstLast({}) → false Exception:java.lang.ArrayIndexOutOfBoundsException: 0 (line number:3) X
sameFirstLast({1, 2, 3, 4, 5, 1}) → true true OK
sameFirstLast({1, 2, 3, 4, 5, 13}) → false false OK
sameFirstLast({13, 2, 3, 4, 5, 13}) → true true OK
sameFirstLast({7, 7}) → true true OK
other tests
please advise
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
numsLen>=1&& is unneccessary
and at that point, you can just
return first==last;
or, using numsLen>=1&& you can make the if(numsLen==0){ unnecessary
and at that point, you can just
return first==last;
or, using numsLen>=1&& you can make the if(numsLen==0){ unnecessary
ASKER
And rather than:
if (first == last)
return true ;
return false ;
you can just return whether "first == last"
return (first == last) ;
instead of doing in 2 steps like checking and then returning we are doing in one step in return itself comparing so that i will automatically give true false in return statement right?
please advise
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
instead of doing in 2 steps like checking and then returning we are doing in one step in return itself comparing so that i will automatically give true false in return statement right?
Yes that's right. We're replacing 3 lines of code with 1 - which is good because it's simpler. And we're also removing a conditional (the "if" test) so the code always executes the same lines of code - which is also good.
Rather than:
if (first == last) {
// Sometimes we run code in here
return true ;
}
// Sometimes we run code here
return false ;
We have now:
// Always run this code
return (first == last) ;
It's best to avoid branches and conditional statements in your code where possible. It makes bugs less likely.
Doug
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Thanx 4 axxepting
ASKER
Open in new window
i think i oredere edge case and passed all tests. I wonder how to improve my code. please advise