这部分其实较为简单,记住常见的操作即可。题目强记即可。

Brian Kernighan 算法

解释:https://www.cnblogs.com/jerryfish/p/15307637.html
image.png

338. 比特位计数

递归对一个数使用 n & (n - 1),消除它右边的0,直到为0停止。

  1. var countBits = function(n) {
  2. const ans = new Array(n + 1).fill(0);
  3. for (let i = 0; i <= n; i++) {
  4. ans[i] = getOneCount(i);
  5. }
  6. function getOneCount(num) {
  7. let count = 0;
  8. while (num > 0) { // 这个写法太棒了,important
  9. num &= num - 1;
  10. count++;
  11. }
  12. // 下面写法就很乱:
  13. // let num = i;
  14. // while (num & (num - 1)) {
  15. // count++; // 满足条件才加1
  16. // num = num & (num - 1);
  17. // }
  18. return count;
  19. }
  20. return ans;
  21. };

231. 2 的幂

  1. var isPowerOfTwo = function(n) {
  2. if (n <= 0) {
  3. return false;
  4. }
  5. // 2.计算n 里 1 的个数
  6. // let count = 0;
  7. // while (n > 0) {
  8. // n = n & (n - 1);
  9. // count++
  10. // }
  11. // if (count === 1) {
  12. // return true;
  13. // }
  14. // return false;
  15. // 2.更直接
  16. return (n & (n - 1)) === 0;
  17. };

461. 汉明距离

还是数1 的个数,只是多一步 异或操作。

  1. var hammingDistance = function(x, y) {
  2. var s = x ^ y; // 多一步异或
  3. let count = 0;
  4. while (s > 0) {
  5. s &= s - 1;
  6. count++;
  7. }
  8. return count;
  9. };

201. 数字范围按位与

这个思路不好理解:按位与呢,只会让数字下降。
image.png

  1. var rangeBitwiseAnd = function(left, right) {
  2. while (left < right) {
  3. right &= right - 1;
  4. }
  5. return right;
  6. };