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;
      }
    }
  • 相关阅读:
    textarea中的空格与换行
    js判断微信内置浏览器
    关于express4不再支持body-parser
    html5 geolocation API
    屏幕密度与分辨率
    nodebeginer
    手机浏览器下IScroll中click事件
    iphone手机上的click和touch
    AngularJS学习笔记一
    不用bootstrap实现居中适应
  • 原文地址:https://www.cnblogs.com/yawenw/p/13033415.html
Copyright © 2011-2022 走看看