leetcode Bulb Switcher

leetcode 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 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.


题目地址:leetcode Bulb Switcher

题意:

给定n,初始的时候灯都是灭的,让你进行进行开关灯。第一轮的时候把1的倍数反转(原来关就开,原来开就关),第二轮把2的倍数翻转,以此类推到第n轮。

求最后灯打开的个数

思路:

我们来分析下:对于素数,那么它仅有1和它本身,最后一定是关掉的。

对一普通的,一定是关掉的,因子成对出现

对于完全平方数,因为有一个倍数不成对出现,所以一定是打开的。比如4 => 1,4   | 2

所以本题就是求1~n有几个完全平方数。

那么,怎么求呢?从1开始到n,每个数测试一下?时间复杂度O(n),太慢

正确的是直接sqrt(n),就可以算出来啦~

原文地址 http://www.hrwhisper.me/leetcode-bulb-switcher/

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



本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Bulb Switcher
本文地址:http://www.hrwhisper.me/leetcode-bulb-switcher/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值