There are n
bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it’s off, or turning off if it’s on). For the i-th round, you toggle every i-th bulb. For the n
-th round, you only toggle the last bulb. Find how many bulbs are on after n
rounds.
n
? For typical LeetCode problems, assume 1 <= n <= 10^9
.i
is toggled in each round k
where k
is a divisor of i
.i
ends up being toggled in each round corresponding to its divisors. Hence a bulb that is toggled an odd number of times will be on at the end.1x36
, 2x18
, 3x12
, 4x9
, 6x6
. Among these, 6 appears only once.n
.n
is floor(sqrt(n))
.#include <cmath>
class Solution {
public:
int bulbSwitch(int n) {
return floor(sqrt(n));
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?