Java递归程序修改:实现整数序列最后零位置输出功能
Java递归实现整数序列最后一个零的位置查找
需求
输入整数序列后输出对应结果:
- 序列中无零则输出0
- 序列中有零则输出最后一个零的序号(序号从1开始)
限制条件
- 禁止使用
operator包 - 无需处理输入错误
- 必须用递归实现遍历逻辑,不能使用for/while/do-while循环
执行步骤
- 输出提示语
count:,读取整数的数量 - 输出提示语
numbers:,读取整数序列 - 输出提示语
result:,后跟计算结果(提示语与结果间用一个空格分隔)
修改后的代码
原代码逻辑为检查序列是否递增,完全不符合需求,以下是重写后的代码:
import java.util.Scanner; public class Main { static Scanner sc; // 递归遍历数字,返回最后一个零的序号(无零则返回0) private static int findLastZero(int remaining, int currentPosition) { if (remaining == 0) { return 0; } int num = sc.nextInt(); int lastZeroFromRest = findLastZero(remaining - 1, currentPosition + 1); // 当前数字是0时,若后续无零则返回当前位置,否则返回后续的最后零位置;非零则直接返回后续结果 return num == 0 ? (lastZeroFromRest == 0 ? currentPosition : lastZeroFromRest) : lastZeroFromRest; } public static void main(String[] args) { sc = new Scanner(System.in); System.out.print("count:"); int count = sc.nextInt(); System.out.println("numbers:"); int result = findLastZero(count, 1); System.out.print("result: " + result); sc.close(); } }
代码说明
- 递归方法
findLastZero通过remaining参数控制递归深度(剩余需要读取的数字个数),currentPosition记录当前数字的序号 - 基准情况:当
remaining为0时,返回0(表示当前分支没有零) - 递归过程:先读取当前数字,再递归处理剩余数字,根据当前数字是否为0,结合递归返回的后续结果,确定最终的最后零位置
内容的提问来源于stack exchange,提问作者snow1e
相关产品推荐
相关产品推荐

