今天我要记录一道我在某公司远程机试遇到的算法题:
输入一个数字n,要求打印出n行数字,规则如下:
1. 所有数字全体是一个首项为1,差值为1的等差数列;
2. 第n行放n个数字,如果n为奇数,则这行的数字从小到大排序;如果n是偶数,则从大到小排序;
3. 最后一行顶格,倒数第二行缩进4个空格,倒数第三行缩进8个空格,以此类推;
4. 每个数字占4个位置,不足的部分用 * 代替。比如99用99**表示,比如100用100*表示;
5. 两个数字之间占四个空格。
java代码实现如下:
1 package com.company; 2 import java.util.*; 3 public class Main{ 4 public static void main(String[] args){ 5 Scanner sc = new Scanner(System.in); 6 String s1="***"; 7 String s2 = "**"; 8 String s3 = "*"; 9 String s4 = " ";//4个空格子 10 int n = sc.nextInt(); 11 StringBuilder sb = new StringBuilder(); 12 for(int i=1;i<=n;i++){ 13 int spaceBeginNum = 4*(n-i);//第i行缩进的空格数 14 int bigNumPerLine = (1+i)*i/2;//第i行的最大数 15 for(int j=0;j<spaceBeginNum;j++){ 16 sb.append(" ");//缩进 17 } 18 if(i%2==0){ 19 //取2的模为0,说明被2整除,是偶数,逆序 20 for(int k=0;k<i;k++){ 21 int targetNum = bigNumPerLine-k; 22 if(targetNum<10){ 23 sb.append(targetNum+s1); 24 }else if(9<targetNum && targetNum<100){ 25 sb.append(targetNum+s2); 26 }else if(targetNum>99 && targetNum<1000){ 27 sb.append(targetNum+s3); 28 }else if(targetNum>999){ 29 sb.append(targetNum); 30 } 31 if(k==i-1){ 32 sb.append("\n"); 33 continue; 34 } 35 sb.append(s4); 36 37 } 38 } else{ 39 //奇数行,正序 40 for(int k=0;k<i;k++){ 41 int targetNum = bigNumPerLine-i+1+k; 42 if(targetNum<10){ 43 sb.append(targetNum+s1); 44 }else if(9<targetNum && targetNum<100){ 45 sb.append(targetNum+s2); 46 }else if(targetNum>99 && targetNum<1000){ 47 sb.append(targetNum+s3); 48 }else if(targetNum>999){ 49 sb.append(targetNum); 50 } 51 if(k==i-1){ 52 sb.append("\n"); 53 continue; 54 } 55 sb.append(s4); 56 57 } 58 } 59 60 } 61 System.out.print(sb); 62 } 63 }
1 package com.company; 2 import java.util.*; 3 public class Main{ 4 public static void main(String[] args){ 5 Scanner sc = new Scanner(System.in); 6 String s1="***"; 7 String s2 = "**"; 8 String s3 = "*"; 9 String s4 = " ";//4个空格子 10 int n = sc.nextInt(); 11 StringBuilder sb = new StringBuilder(); 12 for(int i=1;i<=n;i++){ 13 int spaceBeginNum = 4*(n-i);//第i行缩进的空格数 14 int bigNumPerLine = (1+i)*i/2;//第i行的最大数 15 for(int j=0;j<spaceBeginNum;j++){ 16 sb.append(" ");//缩进 17 } 18 if(i%2==0){ 19 //取2的模为0,说明被2整除,是偶数,逆序 20 for(int k=0;k<i;k++){ 21 int targetNum = bigNumPerLine-k; 22 if(targetNum<10){ 23 sb.append(targetNum+s1); 24 }else if(9<targetNum && targetNum<100){ 25 sb.append(targetNum+s2); 26 }else if(targetNum>99 && targetNum<1000){ 27 sb.append(targetNum+s3); 28 }else if(targetNum>999){ 29 sb.append(targetNum); 30 } 31 if(k==i-1){ 32 sb.append("\n"); 33 continue; 34 } 35 sb.append(s4); 36 37 } 38 } else{ 39 //奇数行,正序 40 for(int k=0;k<i;k++){ 41 int targetNum = bigNumPerLine-i+1+k; 42 if(targetNum<10){ 43 sb.append(targetNum+s1); 44 }else if(9<targetNum && targetNum<100){ 45 sb.append(targetNum+s2); 46 }else if(targetNum>99 && targetNum<1000){ 47 sb.append(targetNum+s3); 48 }else if(targetNum>999){ 49 sb.append(targetNum); 50 } 51 if(k==i-1){ 52 sb.append("\n"); 53 continue; 54 } 55 sb.append(s4); 56 57 } 58 } 59 60 } 61 System.out.print(sb); 62 } 63 }