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
- Extract Single Rotation Logic: We move the step of rotating the array by 1 position into a separate
rotateOncemethod. This isolates the loop-based logic and cleans up therotateByNmethod we need to simplify. - Recursion + Ternary + Comma Operator: Instead of using a
forloop to repeat rotationsntimes, 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 executerotateOnce(in)and then recurse withn-1. This entire logic fits into a single line, which only requires one semicolon. - Preserve Original Behavior: This approach does exactly what your original code does—rotates the array
nsteps 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
相关产品推荐
相关产品推荐

