Code Lab

Mode entretien. Minuteur de 10 min, sans indices ni autocomplétion

Count the ones

MoyenArrays10 min

An array holds only zeros and ones, and it is sorted: all zeros come first, then all ones. Write a function countOnes(bits) that returns how many ones the array has.

  • The array can be empty, or have only zeros, or only ones.
  • The array can be very long, up to a million items. Do not read every item: use the fact that it is sorted.
  • A hidden test counts how many items your code reads from a million-item array. More than 100 reads fail the test. Methods like indexOf, filter and for...of read the items one by one, so they count too.

Exemples

countOnes([0, 0, 1, 1, 1])

Renvoie 3

countOnes([0, 0, 0])

Renvoie 0

countOnes([1, 1])

Renvoie 2

Posé chez Sprinklr · Source

Chargement de l'éditeur...
  1. EntréecountOnes([ 0, 0, 1, 1, 1 ])
    Attendu3
  2. EntréecountOnes([ 0, 0, 0 ])
    Attendu0
  3. EntréecountOnes([ 1, 1 ])
    Attendu2

Les tests cachés se lancent à la soumission