[LeetCode: 319. Bulb Switcher](LeetCode: 319. Bulb Switcher)
题目描述
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 bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Input: 3
Output: 1
Explanation:
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.
解题思路
- 根据题意, 第 i 个灯泡会在 1, …, i (i 的因子) 被切换开关。因此如果 i 的因子个数是奇数,则该灯亮,否则该灯灭
- i 的因子个数是奇数 <==> i 是个完全平方数
- 小于 n 的完全平方数的个数就是 √n 向下取整,因此最终亮着的等的个数是 √n 向下取整
AC 代码
func bulbSwitch(n int) int {
// 1、根据题意, 第 i 个灯泡会在 1, ..., i (i 的因子) 被切换开关
// 因此如果 i 的因子个数是奇数,则该灯亮,否则该灯灭
// 2、i 的因子个数是奇数 <==> i 是个完全平方数
// 3、小于 n 的完全平方数的个数就是 √n 向下取整
return int(math.Sqrt(float64(n)))
}