美文网首页
[刷题防痴呆] 0338 - 比特位计数 (Counting B

[刷题防痴呆] 0338 - 比特位计数 (Counting B

作者: 西出玉门东望长安 | 来源:发表于2022-03-04 03:08 被阅读0次

题目地址

https://leetcode.com/problems/counting-bits/

题目描述

338. Counting Bits

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

 

Example 1:

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:

Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101


思路

  • 方法1, 直接toBinaryString然后count然后count.
  • 方法2, 递归.
  • 方法3, dp.

关键点

代码

  • 语言支持:Java
//方法1, 直接toBinaryString然后count
class Solution {
    public int[] countBits(int n) {
        int[] arr = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            arr[i] = count(i);
        }
        return arr;
    }
    
    private int count(int num) {
        int count = 0;
        String str = Integer.toBinaryString(num);
        for (char c: str.toCharArray()) {
            if (c == '1') {
                count++;
            }
        }
        return count;
    }
}

// 方法2, 递归
class Solution {
    public int[] countBits(int n) {
        int[] arr = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            arr[i] = count2(i);
        }
        return arr;
    }

    private int count2(int num) {
        if (num == 0) {
            return 0;
        }
        if (num % 2 == 0) {
            return count2(num / 2);
        } else {
            return count2(num - 1) + 1;
        }
    }
}

// 方法3, dp
class Solution {
    public int[] countBits(int n) {
        int[] arr = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            arr[i] = arr[i / 2] + (i & 1);
        }
        return arr;
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0338 - 比特位计数 (Counting B

      本文链接:https://www.haomeiwen.com/subject/hrhprrtx.html