2639. Find the Width of Columns of a Grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public int[] findColumnWidth(int[][] grid) {
int m = grid.length, n = grid[0].length;

int[] ans = new int[n];
for (int j = 0; j < n; j++) {
int min = grid[0][j], max = grid[0][j];
for (int i = 1; i < m; i++) {
min = Math.min(min, grid[i][j]);
max = Math.max(max, grid[i][j]);
}

ans[j] = Math.max(getWidth(min), getWidth(max));
}

return ans;
}

private int getWidth(int num) {
if (num == 0) {
return 1; // 注意数字 0 的宽度为 1 而不是 0
}

int width = 0;
if (num < 0) {
width++;
num = -num;
}

while (num > 0) {
width++;
num /= 10;
}

return width;
}
}

References

2639. Find the Width of Columns of a Grid