灯泡开关 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 th round, you toggle every i bulb. For the th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.spa

Example:three

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.

解决:it

【题意】这道题给了咱们n个灯泡,第一次打开全部的灯泡,第二次每两个更改灯泡的状态,第三次每三个更改灯泡的状态,以此类推,第n次每n个更改灯泡的状态。让咱们求n次后,全部亮的灯泡的个数。io

例如:只有5个灯泡的状况,'X'表示灭,‘√’表示亮,以下所示:ast

初始状态:    X    X    X    X    Xclass

第一次:      √    √    √    √    √循环

第二次:      √     X    √    X    √时间

第三次:      √     X    X    X    √lbs

第四次:      √     X    X    √    √

第五次:      √     X    X    √    X

① 直接解决,使用一个数组记录每一个位置上灯泡的状态,每次循环更改这些状态。时间复杂度为O(N^2)。超时。

② 找规律。计算亮的灯泡的个数,能够找到以下规律:

共有1 ~ 3个灯泡:最终亮的灯泡个数

共有4 ~ 8个灯泡:最终亮的灯泡个数 2

共有9 ~ 15个灯泡:最终亮的灯泡个数 3

共有16 ~ 24个灯泡:最终亮的灯泡个数 4

共有25 ~ 35个灯泡:最终亮的灯泡个数 5

......

因此,有n个灯泡时,只须要找到一个最大的彻底平方数的值小于等于该数便可。

class Solution {//0ms     public int bulbSwitch(int n) {         int res = (int)Math.sqrt(n);         return res;     } }

相关文章
相关标签/搜索