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 ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3.
At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on, on, on]. After second round, the three bulbs are [on, off, on]. After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
Subscribe to see which companies asked this question
class Solution(object): def bulbSwitch(self, n): """ :type n: int :rtype: int n=8 0,00000000 1,11111111 2,10101010 3,10001110 4,10011111 5,10010111 6,10010001 7,10010001 8,10010000=>2 bit 1=>1 bit 2=>0 bit 3=>0 bit 4=>1,2,4=>1 bit 5=>1,5=>0 bit 6=>1,2,3,6=>0 bit 7=>1,7=>0 bit 8=>1,2,4,8=>0 bit 9=>1,3,9=>1 bit 10=>1,2,5,10=>0 bit 11=>1,11=>0 bit 12=>1,2,3,4,6,12=>0 bit 13=>1,13=>0 bit 14=>1,2,7,14=>0 bit 15=>1,3,5,15=>0 bit 16=>1,2,4,8,16=>1 only if bit n is a square number """ ans = 0 i = 1 while i*i <= n: i += 1 ans += 1 return ans