面试题——把1、2、3、4、……按如下规律排列
题目:
答案(Java):
//获取行列 public static int[] getCell(int n) { if (n<1) return null; if (n<6) return new int[]{1, n-1}; //n大于5以后每行4个数,所以n-5除以4就得到行(这里算出的行是从0开始) int row = (n-5)/4; //所以n-5模4就得到列 int idx = (n-5)%4; //如果n-5不能整除4,则行数+1 row += (idx == 0) ? 0 : 1; //根据行的奇偶性修改列顺排还是逆排 if (row%2 == 1) { //逆排的时候 idx = (4-idx)%4; } else { //顺排的时候 if (idx==0) idx = 4; } //因为题目要求行从1开始,所以行+1 return new int[] {row+1, idx}; } public static void test(int n) { for (int i=1; i<=n; i++) { int[] cell = getCell(i); System.out.printf("%d在%d行%c列 ", i, cell[0], A+cell[1]); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.printf("请输入一个正整数:"); int n = sc.nextInt(); //int n = 2013; int[] cell = getCell(n); if (cell != null) { System.out.printf("%d在%d行%c列 ", n, cell[0], A+cell[1]); } else { System.out.printf("%d不在范围内! ", n); } }