Bulb Switcher 题解

    xiaoxiao2021-03-25  103

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

    题目链接:319. Bulb Switcher

    算法描述:

    由题意知,给定 n 个灯泡,我们将进行开关转换(开->关 或 关->开),灯泡初始情况是灭的。第一次,每隔一个灯泡进行一次转换(即每个灯泡都将转换一次);第二次,每隔两个灯泡进行一次转换(即灯泡2,4,6,8……)

    ;第三次,每隔三个灯泡转换一次(即灯泡3,6,9,12……);……依次进行。执行完 n 次后,我们将返回开着的灯泡个数。

    我们对以上进行归纳:当开关拨动次数为偶数时灯将熄灭(关),拨动次数为奇数时灯将亮起(开)。第 i 轮,灯泡是否被转换波动取决于它能否被 i 整除。1的因数有1(开);2的因数有1,2(关);3的因数1,3(关);4的因数1,2,4(开);5的因数1,5(关);6的因数1,2,3,6(关);7的因数1,7(关);8的因数1,2,4,8(关);9的因数1,3,9(开);……可以发现,完全平方数就是我们所求的。

    因此我们求出不大于 n 的完全平方数的个数即可。

    代码:

    class Solution { public: int bulbSwitch(int n) { int ans=0; for(int i=1; i*i<=n; i++){ ans++; } return ans; } };

    转载请注明原文地址: https://ju.6miu.com/read-10823.html

    最新回复(0)