https://leetcode.com/problems/score-after-flipping-matrix/
I couldn't come up with this solution. The official solution is great. It is amazing to set the all bits on the left column at first.
var matrixScore = function (grid) {
let m = grid.length;
let n = grid[0].length;
for (let i = 0; i < m; i++) {
if (grid[i][0] === 0) {
for (let j = 0; j < n; j++) {
grid[i][j] = 1 - grid[i][j];
}
}
}
for (let j = 1; j < n; j++) {
let countZero = 0;
for (let i = 0; i < m; i++) {
if (grid[i][j] === 0) {
countZero += 1;
}
}
if (countZero > m - countZero) {
for (let i = 0; i < m; i++) {
grid[i][j] ^= 1;
}
}
}
let score = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
let columnScore = grid[i][j] << (n - j - 1);
score += columnScore;
}
}
return score;
};