Bulb Switcher解题报告

Description:

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.

Link:

https://leetcode.com/problems/bulb-switcher/description/

解题方法:

一开始用brute force,妥妥的超时,看过discuss以后才知道以下解法:

比如从上面例子当n = 3时,有[on, off, off]
当n = 4时,前面三个灯泡与n = 3时相同,所以取决于第四个💡是不是亮。
所以,
第几个💡是亮还是灭,取决于它被toggle几次,也就是取决于它有几个系数,比如第四个灯泡的系数为:1,2,4。这个灯泡就是亮的。
由此上信息可以知道,想知道第几个灯泡是亮还是灭,只要知道它系数的个数是奇数(亮)还是偶数(灭)。
而当一个数是平方数的时候,它的系数个数是奇数个。
所以,本题的解答变成统计从1~n有多少个平方数,即为从1~n有多少个亮的💡。

Time Complexity:

O[N^(1/2)]

完整代码:

int bulbSwitch(int n) 
    {
        if(n == 0)
            return 0;
        int count = 0;
        for(int i = 1; i*i <= n; i++ )
            count++;
        return count;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,494评论 0 23
  • 我曾经说我最讨厌的就是按部就班的生活,可是我现在过的就是我曾经口中最讨厌的生活。朝九晚六,下班之时已是夜幕四合...
    鱼飞上天阅读 1,643评论 0 0
  • 阳光明媚的周六,带着孩子来到了合一农场,今天有胡萝卜嘉年华,可以体验胡萝卜丰收的喜悦。 一进入农场,初春的气息扑面...
    VivyYNSH阅读 3,633评论 0 2
  • 一转眼到了第四阶段的总结啦。已经80天了。每天的写作内容也升级到了500字。这一阶段,使用了几次请假。这20天有太...
    大果果ly阅读 1,198评论 0 0
  • 简悦直播教练恬源阅读 1,463评论 2 1

友情链接更多精彩内容