338. Counting Bits

El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

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

Ejemplo:

Input: n = 5

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

Explanation:

0 --> 0

1 --> 1

2 --> 10

3 --> 11

4 --> 100

5 --> 101

C# solución

coincidente/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++ solución

borrador 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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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

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

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

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

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

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

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

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.