dimanche 3 mars 2019

Codility test : Cannot find the number of bits set to 1 in the binary representation of the number 3*K

I tried to solve this : A non-empty array A consisting of N integers is given. The array is sorted in ascending order and it does not contain duplicate values. The array describes a number K as follows:

K = pow2(A[0]) + pow2(A[1]) + ... + pow2(A[N-1])
pow2(L) = 2L

For example, consider array A consisting of three elements such that

A[0] = 1    A[1] = 4    A[2] = 5

It describes the number K = 50, because

 pow2(A[0]) + pow2(A[1]) + pow2(A[2]) =
 pow2(1)    + pow2(4)    + pow2(5)    =
 2          + 16         + 32         = 50

Write a function

function solution($A);

that, given a non-empty array A consisting of N non-negative integers, returns the number of bits set to 1 in the binary representation of the number 3*K, where K is the number described by array A.

For example, given array A consisting of three elements such that

A[0] = 1    A[1] = 4    A[2] = 5

the function should return 4 because:

array A represents number K = 50, as explained above;

3 * K = 3 * 50 = 150;

the binary representation of 150 is 10010110; it contains four bits set to 1. Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..10,000];

each element of array A is an integer within the range [0..1,000,000,000]; array A is sorted in non-decreasing order; array A does not contain duplicates.

I got only 33% on this problem. Can someone have a clue in php ?

My solution below :

function solution($N) {
    $constant = 3;
    $arrayPower = array();
    foreach($N as $value) {
        $arrayPower[] = bcpowmod(2, $value, 1000000000);
    }
    $binaryNumber = decbin(array_sum($arrayPower)*3);
    return strlen(str_replace(0,'',$binaryNumber));
}

Aucun commentaire:

Enregistrer un commentaire