题目地址
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;
}
}
网友评论