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.
提示
:
提交代码后
,
需要用简洁的语言解释一下代码思路
~
谢谢
历史题目和总结见公众号「每日一道算法题」
https://leetcode.com/problems/bulb-switcher/description/
题目大意
这儿有n个灯泡被初始化。
首先,你点亮所有的灯泡。
然后,你关掉每第二个灯泡。
在第三回,你切换每第三个灯泡(如果它是关闭的则开启它,如果它是开启的则关闭它)。
对于第i回,你切换每第i个灯泡。
对于第n回,你仅仅切换最后一个灯泡。
找出在n回之后还有多少个灯泡是亮着的。
题目解析