You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java递归程序修改:实现整数序列最后零位置输出功能

Java递归实现整数序列最后一个零的位置查找

需求

输入整数序列后输出对应结果:

  • 序列中无零则输出0
  • 序列中有零则输出最后一个零的序号(序号从1开始)

限制条件

  • 禁止使用operator包
  • 无需处理输入错误
  • 必须用递归实现遍历逻辑,不能使用for/while/do-while循环

执行步骤

  1. 输出提示语count:,读取整数的数量
  2. 输出提示语numbers:,读取整数序列
  3. 输出提示语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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:45:38