zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge28 之 DP+位运算

    4种解法

    1.pop count

    public class Solution {
        public int[] countBits(int num) {
            int[] ans = new int[num + 1];
            for (int i = 0; i <= num; ++i)
                ans[i] = popcount(i);
            return ans;
        }
        private int popcount(int x) {
            int count;
            for (count = 0; x != 0; ++count)
              x &= x - 1; //zeroing out the least significant nonzero bit
            return count;
        }
    }

    2.DP + Most Significant Bit

    public class Solution {
        public int[] countBits(int num) {
            int[] ans = new int[num + 1];
            int i = 0, b = 1;
            // [0, b) is calculated
            while (b <= num) {
                // generate [b, 2b) or [b, num) from [0, b)
                while(i < b && i + b <= num){
                    ans[i + b] = ans[i] + 1;
                    ++i;
                }
                i = 0;   // reset i
                b <<= 1; // b = 2b
            }
            return ans;
        }
    }

    3.DP + Least Significant Bit

    public class Solution {
      public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i >> 1] + (i & 1); // x / 2 is x >> 1 and x % 2 is x & 1
          return ans;
      }
    }

    4.DP + Last Set Bit

    public class Solution {
      public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i & (i - 1)] + 1;
          return ans;
      }
    }
  • 相关阅读:
    Django部分面试题目
    网编部分
    面试题
    mysql安装
    并发编程
    集合以及深浅拷贝和和小数据池--个人一些经验总结
    稍微比较全的那种字典
    个人声明
    python
    python-pdf文件(持续更新
  • 原文地址:https://www.cnblogs.com/yawenw/p/13033415.html
Copyright © 2011-2022 走看看