I have been struggling with this java problem for several days now, and now I have to give up. I have been told the answer which should be 5 5 3 3, but I cannot in any way see how it is possible to get that result.
Given the following java method:
public int[] methodName(int[] nums)
{
int largestOdd=0;
for(int i=nums.length-2;i>=0;i--)
{
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1];
if (nums[i] == 0)
nums[i] = largestOdd;
}
return(nums);
}
What is printed when the following Java statements are executed?
int[] nums = {0,5,0,3};
nums = methodName(nums)
for (int i = 0; i<nums.length;i++)
System.out.print(nums[i] + "");
System.out.println();
It just doesnt make any sense for me that first of all it will start printing "5". In my opinion it should be "3" because nums[2+1] = 3 (last index element)
Second of all why will it print four numbers when the loop in the method only will loop through 3 times until hitting -1 ?
If someone can explain how to get the result in a understandable way, I would be very happy.
Thanks in advance