• 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;
      }
    }
  • 相关阅读:
    DAO模式多表联查
    使用ADO.NET访问数据库
    连接查询和分组查询
    模糊查询和聚合函数
    poj 1220 NUMBER BASE CONVERSION
    poj 1964 City Game
    Odd number problem
    POJ 2983 M × N Puzzle
    L O V E
    【Mybatis】【3】处理大于号小于号及其他特殊字符
  • 原文地址:https://www.cnblogs.com/yawenw/p/13033415.html
Copyright © 2020-2023  润新知