338. 比特位计数

题目:

338. 比特位计数
338. 比特位计数_第1张图片

题解:

  1. 解释一:
    在这里插入图片描述
  2. 解释二:
    338. 比特位计数_第2张图片
  3. 解释三:
    338. 比特位计数_第3张图片
  4. 解释四:
    338. 比特位计数_第4张图片

1. 题解一:动态规划 + 最低有效位

在这里插入图片描述
338. 比特位计数_第5张图片

2. 题解二:动态规划 + 最后设置位

在这里插入图片描述
338. 比特位计数_第6张图片

代码:

1. 代码一:动态规划 + 最低有效位

import java.util.*;

public class code338 {

    // 方法1: 动态规划 + 最低有效位
    public static int[] countBits(int num) {
        int res[] = new int[num + 1];
        for(int i = 1; i <= num; i++)
        {
            res[i] = res[i >> 1] + (i & 1); // (x / 2) is (x >> 1) and (x % 2) is (x & 1), 注意 (i & 1) 需要加括号
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt())
        {
            int num = sc.nextInt();
            int res[] = countBits(num);
            for(int i = 0; i <= num; i++)
            {
                System.out.print(res[i] + " ");
            }
            System.out.println();
        }
    }
    
}

2. 代码二:动态规划 + 最后设置位

import java.util.*;

public class code338 {

    // 方法2: 动态规划 + 最后设置位
    public static int[] countBits(int num) {
        int res[] = new int[num + 1];
        for(int i = 1; i <= num; i++)
        {
            res[i] = res[i & (i - 1)] + 1; // 注意要从1开始,0不满足
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt())
        {
            int num = sc.nextInt();
            int res[] = countBits(num);
            for(int i = 0; i <= num; i++)
            {
                System.out.print(res[i] + " ");
            }
            System.out.println();
        }
    }
    
}

参考:

  1. 比特位计数
  2. 清晰的思路
  3. 位运算基础知识
  4. 动态规划(位运算性质) python3
  5. 最清晰的动态规划解题思路分析

你可能感兴趣的:(热题,HOT,100,动态规划,位运算)