算法小路

方向矩阵

// →为初始方向
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
for (int i = 1, x = 0, y = 0, d = 0; i <= n * n; i ++ ) {
    res[x][y] = i;
    int a = x + dx[d], b = y + dy[d];
    if (a < 0 || a >= n || b < 0 || b >= n || res[a][b]) {
        d = (d + 1) % 4;
        a = x + dx[d], b = y + dy[d];
    }
    x = a, y = b;
}

n&(n-1)

原理

n 的二进制表示中的最低位为 1 的改为 0

应用

n 1 0 1 0 0
n-1 1 0 0 1 1
n & ( n - 1) 1 0 0 0 0
//二进制中1的个数
class Solution {
public:
    int NumberOf1(int n) {
        int res = 0;
        while(n)
        {
            n &= (n - 1);
            res++;
        }
        return res;
    }
};
posted @ 2022-10-25 10:11  当惜  阅读(25)  评论(0)    收藏  举报