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

Java中仅用一个分号实现int数组旋转的技术问询

Reduce Semicolons in rotateByN to Just One

First, let's break down the problem: your original rotateByN uses nested loops that introduce multiple semicolons, and we need to trim that down to exactly one semicolon in the method body. Here's a working solution that keeps the core functionality intact while meeting the requirement:

public class Four {
    static void rotateOnce(int[] in) {
        int tmp = in[0];
        for (int i = 1; i < in.length; i++) in[i - 1] = in[i];
        in[in.length - 1] = tmp;
    }

    static void rotateByN(int[] in, int n) {
        n > 0 ? (rotateOnce(in), rotateByN(in, n - 1)) : null;
    }

    public static void main(String[] args) {
        int[] arr = { 2, 7, 6, 1, 0 };
        rotateByN(arr, 3);
        for (int r : arr) System.out.println(r);
    }
}

How This Works

  1. Extract Single Rotation Logic: We move the step of rotating the array by 1 position into a separate rotateOnce method. This isolates the loop-based logic and cleans up the rotateByN method we need to simplify.
  2. Recursion + Ternary + Comma Operator: Instead of using a for loop to repeat rotations n times, we use recursion. The ternary operator checks if we still need to perform rotations (n > 0). If true, we use the comma operator to first execute rotateOnce(in) and then recurse with n-1. This entire logic fits into a single line, which only requires one semicolon.
  3. Preserve Original Behavior: This approach does exactly what your original code does—rotates the array n steps by shifting the first element to the end each time—while modifying the input array directly (no new array created).

Test Output

Running the main method will produce the same result as your original code:

1
0
2
7
6

内容的提问来源于stack exchange,提问作者hwgn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:23:05