Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

swapEnds challenge

Hi,

I am working on belw challenge
http://codingbat.com/prob/p118044
i wrote as below and passed all tests.

public int[] swapEnds(int[] nums) {
int len=nums.length;

  int[] newNums=new int[len];
  for(int i=0;i<len;i++){
  
  newNums[i]=nums[i];
  
  }
  
 newNums[0]= nums[len-1];
 newNums[len-1]=nums[0];
 return newNums;
}

Open in new window


How to improve my code and alternate ways of ding it. Please advise
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
it would be sufficient to loop for(int i=1;i<len-1;i++){
Avatar of gudii9

ASKER

int t=nums[0];
 nums[0]=nums[nums.length-1];
  nums[nums.length-1]=t;
return nums;

instead of above can we write like below without t?


  nums[0]=nums[nums.length-1];
  nums[nums.length-1]=nums[0];
 return nums;
Avatar of gudii9

ASKER

i think i got it. Since you are putting last in first so first needs to be saved somewhere to use later
Avatar of gudii9

ASKER

it would be sufficient to loop for(int i=1;i<len-1;i++){

this i will fix next time
instead of above can we write like below without t?


  nums[0]=nums[nums.length-1];
  nums[nums.length-1]=nums[0];
 return nums;
No,  nums[0] would have the same value as nums[nums.length-1];