我几天来一直在努力解决这个java问题,现在我不得不放弃。我被告知答案应该是5 5 3 3,但我不能以任何方式看到如何获得这个结果。
给出以下java方法:
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);
}
执行以下Java语句时打印的内容是什么?
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();
对我来说没有任何意义,首先它将开始打印“5”。在我看来它应该是“3”因为nums [2 + 1] = 3(最后一个索引元素)
其次,为什么当方法中的循环只循环3次直到达到-1时,它会打印四个数字?
如果有人可以解释如何以可理解的方式获得结果,我会非常高兴。
提前致谢
答案 0 :(得分:2)
methodName
向后遍历数组,检查每对数字。在这种情况下,检查的第一对将是(0,3)。
当它在对上运行时,methodName
会跟踪看到的最大奇数(它会查看每对的第二个号)。
每当第一个数字为零时,它就会将其设置为目前为止看到的最大奇数。
所以在这种情况下,它会:
答案 1 :(得分:0)
{0,5,0,3}
for(int i=nums.length-2;i>=0;i--) // starts at 0 (index 2) <-> num.length 4 - 2
// runs 3 times num.length(4) - 2 = 0
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1]; <--> // 3
// if odd and grater than 0
// first iteration largestOdd = 3
if (nums[i] == 0) // still i is index 2 {0, 5, 0, 3} = 0, so true
nums[i] = largestOdd; // nums[i] (index 2) = 3
// after first iteration
{0, 5, 3, 3}
Second iteration do nothing (0 is not odd)
Third iteration, do same as first iteration, making final array
{5, 5, 3, 3}
下一部分
// This method returns the same array you passed into to
public int[] methodName(int[] nums)
{
return(nums);
}
// So
nums = methodName(nums) = {5, 5, 3, 3} The new array produced by the method
答案 2 :(得分:0)
you can analyse step by step.
In the for-loop: i starts from 2 to 0;
num = [0,5,0,3]
1.
i = 2; largestOdd = 0; nums[i+1] = nums[3] = 3; nums[i] = nums[2] = 0;
first condition "(nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)" is true
largestOdd = nums[i+1] = 3
second condition (nums[i] == 0) is true
nums[i] = nums[2] = largestOdd = 3
nums = [0,5,3,3];
2.
i=1; largestOdd = 3; nums[i+1] = nums[2] = 3; nums[i] = nums[1] = 5;
first condition is false;
second condition is false;
nums = [0,5,3,3];
3.
i=0; largestOdd = 3; nums[i+1] = nums[1] = 5; nums[i] = nums[0] = 0;
first condition is true
largestOdd = 5;
second condition nums[0] = 0 is true
nums[0] = largestOdd = 5;
nums = [5,5,3,3];
答案 3 :(得分:0)
Loop 1 start i=2,nums=[0,5,0,3],largestOdd=0
because:(nums[2+1]=3)/2 !=0 && (nums[2+1]=3)>(largestOdd=0)
so:largestOdd=(nums[2+1]=3)=3
beacuse:(nums[2]=0) ==0
so:nums[2]=(largestOdd=3)=3
Loop 1 end i=2,nums=[0,5,3,3],largestOdd=3
Loop 2 start i=1,nums=[0,5,3,3],largestOdd=3
because:(nums[1+1]=3)/2 !=0 && (nums[1+1]=3)>(largestOdd=3)
so:next
beacuse:(nums[1]=5) !=0
so:next
Loop 2 end i=1,nums=[0,5,3,3],largestOdd=3
Loop 3 start i=0,nums=[0,5,3,3],largestOdd=3
because:(nums[0+1]=5)/2 !=0 && (nums[0+1]=5)>(largestOdd=3)
so:largestOdd=(nums[0+1]=5)=5
beacuse:(nums[0]=0) ==0
so:nums[0]=(largestOdd=5)=5
Loop 3 end i=0,nums=[5,5,3,3],largestOdd=5
END LOOP