leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

bulb-switcher.js (760B)


      1 //Create the algorithm to switch bulbs from on to off.
      2 //This is done by creating an array of length n. From there
      3 //you need to iterate through the list and switch each value
      4 //that is divisible by the current index then return the number of on
      5 //switches. The time complexity of this code is O(n * sqrt(n))
      6 //Runtime: 1801ms Beats: 5.17%
      7 //Memory: 121.8MB Beats: 6.90%
      8 /**
      9  * @param {number} n
     10  * @return {number}
     11  */
     12 var bulbSwitch = function(n) {
     13     let bulbs = Array(n).fill(1);
     14     for(let i = 1; i < n ; ++i){
     15         for(let x = i ; x < n ; x += i + 1){
     16             bulbs[x] = bulbs[x] * -1;
     17         }
     18     }
     19     let on = 0;
     20     for(let i = 0 ; i < bulbs.length ; ++i){
     21         if(bulbs[i] == 1){
     22             on += 1;
     23         }
     24     }
     25     return on;
     26 };