gpt4 book ai didi

java - codingbat 递归练习

转载 作者:行者123 更新时间:2023-11-29 07:32:21 26 4
gpt4 key购买 nike

我目前正在 codingbat 网站上做一个练习,上面写着:

Given an array of ints, compute recursively if the array contains a 6. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.

示例:

array6([1, 6, 4], 0) → true

array6([1, 4], 0) → false

array6([6], 0) → true

我的解决方案如下,但出于某种原因,当我的 if(nums[index] == 6) 为真时,它仍会执行 else block 中的代码。

我的问题:

从技术上讲,当 if 语句 中的代码被执行时,它不应该执行 else block 中的代码。那么为什么这种情况会持续存在?;

public static boolean array6(int[] nums, int index) { 

if(nums.length == 0){
return false;
}

if(index == nums.length-1 && nums[index] != 6){
return false;
}

if(index == nums.length-1 && nums[index] == 6){
return true;
}

if(nums[index] == 6){
return true;

}else{
array6(nums,index+1);
}

return false;
}

最佳答案

通过递归返回您收到的值。改变

array6(nums,index+1);

类似于

return array6(nums,index+1);

关于java - codingbat 递归练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40332136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com