第一种方法:
生成杨辉三角的方法不行,会出现越界,
数组从[0][0]开始,i行j列
只看列
每一行的最右侧坐标为2*i,下坐标为
0,
0,1,2
0,1,2,3,4
…
n的范围1≤n≤10的9次方
这是本地上测试的代码
import java.util.Scanner;public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别int n = sc.nextInt();int[][] nums = new int[n][((n+1)*2-1) -1];for (int i = 0; i < n; i++) {for (int j = 0; j <= 2*i; j++) {// ((i + 1) * 2 - 1) - 1 每行的个数是1,3,5,7...if (j == 0 || j == 2*i) {//每行第1个、倒数第1个nums[i][j] = 1;}else if (j == 1 || j == 2*i - 1) {//每行第2个、倒数第2个if (j == 1){if(j - 1 < 0 ) nums[i][j] = nums[i - 1][j];else nums[i][j] = nums[i - 1][j - 1] + nums[i - 1][j];}else if (j == 2*i - 1) nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1];} else {if(j == 1) nums[i][j] = nums[i - 1][j - 1] + nums[i - 1][j];//没有上一行[j-2]else if(j == 2*i -1) nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1];//没有上一行[j]//else if(j > (i-1)*2 ) nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1];//没有[i-1][j]else nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1] + nums[i - 1][j];}}}//输出杨辉三角for(int i = 0; i < nums.length; i++){for(int j = 0; j <= ((i + 1) * 2 - 1) - 1; j++){System.out.print(nums[i][j] + " ");}System.out.println();}System.out.println("-----------------");//输出每一行的第一个偶数在第几位int res = -1;for (int i = 0; i < n; i++) {for (int j = 0; j <= 2 * i; j++) {if (nums[i][j] % 2 == 0) {res = j + 1;System.out.println(res);break;}else if(j == 2*i && res==-1) System.out.println(res);}res = -1;}}
}
这是跑出来的结果
import java.util.Scanner;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别int n = sc.nextInt();int[][] nums = new int[n][((n + 1) * 2 - 1) - 1];for (int i = 0; i < n; i++) {for (int j = 0; j <= 2 * i; j++) { // ((i + 1) * 2 - 1) - 1 每行的个数是1,3,5,7...if (j == 0 || j == 2 * i) { //每行第1个、倒数第1个nums[i][j] = 1;} else if (j == 1 || j == 2 * i - 1) { //每行第2个、倒数第2个if (j == 1) {if (j - 1 < 0 ) nums[i][j] = nums[i - 1][j];else nums[i][j] = nums[i - 1][j - 1] + nums[i - 1][j];} else if (j == 2 * i - 1) nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1];} else {if (j == 1) nums[i][j] = nums[i - 1][j - 1] + nums[i -1][j]; //没有上一行[j-2]else if (j == 2 * i - 1) nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j -1]; //没有上一行[j]else nums[i][j] = nums[i - 1][j - 2] + nums[i - 1][j - 1] + nums[i - 1][j];}}}int res = -1;for (int i = 0; i < nums[n - 1].length; i++) {if (nums[n - 1][i] % 2 == 0) {res = i+1;break;}}System.out.println(res);}
}
第二种方法:
使用规律coding
import java.util.Scanner;// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int res;if(n == 1 || n == 2){res = -1;}else{if((n-2) % 2 == 1) res = 2;else if((n-2) % 4 == 2) res = 3;else res = 4;}System.out.println(res);}
}