【LEETCODE】319-Bulb Switcher

来源:互联网 发布:vb.net udp通讯 编辑:程序博客网 时间:2024/05/29 19:19

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 nth round, you only toggle the last bulb. Find how many bulbs are on aftern 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 个灯泡,初始状态是off,

第一轮:全部变成on

第二轮:每两个一组,把第二个切换一下

第三轮:每三个一组,把第三个切换一下

。。。

第n轮:全部n个一组,把第n个切换一下

在这n轮之后,找出有多少个灯泡是on


思路:

小于等于n的每个数字,各有几个无重复的因子,因子包括1及其自身

因子的个数为奇数个时,n轮过后就是on

返回有几个是奇数个因子的


而因子都是成对出现的,之所以出现了奇数个因子,是因为有个因子的平方=这个数

即此数为完全平方数


对n开平方,则小于等于n的 完全平方数 的个数 就是n开方后取整




class Solution(object):    def bulbSwitch(self, n):        """        :type n: int        :rtype: int        """        return int(math.sqrt(n))




0 0