小米后台笔试2048问题吐槽
我的代码过了75%的案例,看了别人的AC代码,对于某一行2 0 2 0的数据,0不是表示空吗,别人AC代码的处理结果是2 2 0 0,我的代码处理结果是4 0 0 0,下面是我随便找了个2048小游戏玩了下:
#小米##笔试题目##吐槽#
左图往左移后的结果
补充我的代码:
import java.util.Scanner; public class Main { public static void qzero(int [][] game, int n, int index) { int i = 0; for (int j = 0; j < n; j++) { if (game[index][j] != 0) { game[index][i++] = game[index][j]; } } for (int j = i; j < n; j++) { game[index][j] = 0; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int [][] game = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { game[i][j] = sc.nextInt(); } } for (int i = 0; i < n; i++) { // 遍历i行 qzero(game, n, i); for (int j = 0; j < n - 1; j++) { if (game[i][j] == game[i][j + 1]) { //前两个合并 game[i][j] += game[i][j]; game[i][j + 1] = 0; j ++; } } qzero(game, n, i); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j != 0) { System.out.print(" "); } System.out.print(game[i][j]); } System.out.println(); } } }