题解 | #尼科彻斯定理#
尼科彻斯定理
https://www.nowcoder.com/practice/dbace3a5b3c4480e86ee3277f3fe1e85
//hj76 //奇数和偶数表达方式略微不同, 本来想奇数偶数合并觉得太麻烦索性就分开写了 //先把中间的两个数找到, 再向两边延申, 注意数组下标是2n和2n+1, 需要延申n/2次 import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int []arr = new int[n]; int k = n*n; int a,b; if(n%2==0)//偶数 { a=k-1; b=k+1; for (int i = 0; i < n/2; i++) { arr[2*i] = a; arr[2*i+1] = b; a-=2; b+=2; } } else//奇数 5 5/2=2 { a= k-2; b= k+2; arr[n-1] = k; for (int i = 0; i < n/2; i++) { arr[2*i] = a; arr[2*i+1] = b; a-=2; b+=2; } } Arrays.sort(arr); String str = ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(arr[i]).append("+"); } sb.deleteCharAt(sb.length()-1); System.out.println(sb.toString()); } }
华为机试题解 文章被收录于专栏
华为机试题解