[leetcode]319. Bulb Switcher

来源:互联网 发布:python教学视频知乎 编辑:程序博客网 时间:2024/06/05 02:38

题目链接:https://leetcode.com/problems/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 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.

解题思路:开关被拨动次数为偶数时,灯为关,拨动次数为奇数时,灯为开。第n个灯最后是否亮与其与其因子有关,灯拨动次数等于因子数

1  因子:1

2  因子:1 、2

3  因子:1、3

4  因子:1、2、4

5  因子:1、5

不难发现,n为某数平方数,因子有奇数个,那么最终肯定为亮。


class Solution{public:    int bulbSwitch(int n)    {        return (int)sqrt(n);    }};


0 0
原创粉丝点击