338. Counting Bits

O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.

given inteiro n, return array ans длиной n + 1, такой что для каждого i (0 <= i <= n), ans[i] будет равняться количеству единиц в двоичном представлении числа i.

Exemplo:

Input: n = 5

Output: [0,1,1,2,1,2]

Explanation:

0 --> 0

1 --> 1

2 --> 10

3 --> 11

4 --> 100

5 --> 101

C# solução

correspondente/original
public class Solution {
    public int[] CountBits(int num) {
        int[] ans = new int[num + 1];
        for (int x = 1; x <= num; ++x) {
            ans[x] = ans[x & (x - 1)] + 1;
        }
        return ans;
    }
}

C++ solução

rascunho automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& CountBits(int num) {
        vector<int>& ans = new int[num + 1];
        for (int x = 1; x <= num; ++x) {
            ans[x] = ans[x & (x - 1)] + 1;
        }
        return ans;
    }
}

Java solução

correspondente/original
public class Solution {
    public int[] countBits(int num) {
        int[] ans = new int[num + 1];
        for (int x = 1; x <= num; ++x) {
            ans[x] = ans[x & (x - 1)] + 1;
        }
        return ans;
    }
}

JavaScript solução

correspondente/original
var countBits = function(num) {
    let ans = new Array(num + 1).fill(0);
    for (let x = 1; x <= num; x++) {
        ans[x] = ans[x & (x - 1)] + 1;
    }
    return ans;
};

Python solução

correspondente/original
class Solution:
    def countBits(self, num: int) -> List[int]:
        ans = [0] * (num + 1)
        for x in range(1, num + 1):
            ans[x] = ans[x & (x - 1)] + 1
        return ans

Go solução

correspondente/original
func countBits(num int) []int {
    ans := make([]int, num + 1)
    for x := 1; x <= num; x++ {
        ans[x] = ans[x & (x - 1)] + 1
    }
    return ans
}

Algorithm

Инициализация arrayа:

Создайте array ans длиной n + 1, заполненный нулями. Этот array будет содержать количество единиц в двоичном представлении каждого числа от 0 до n.

Итерация и вычисление:

Пройдите в цикле по всем числам от 1 до n. Для каждого числа x используйте битовую операцию x & (x - 1), чтобы убрать последнюю установленную биту, и добавьте 1 к значению ans для этого результата. Это количество единиц в двоичном представлении числа x.

Возврат результата:

return заполненный array ans, который содержит количество единиц для каждого числа от 0 до n.

😎

Vacancies for this task

vagas ativas with overlapping task tags are mostradas.

Todas as vagas
Ainda não há vagas ativas.