LeetCode-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.
共有n个灯泡,初始状态是关闭的。第一轮,打开所有灯泡,第二轮关掉所有2的倍数的灯泡,第三轮转换所有3的倍数的灯泡开关状态,以此类推,知道第n轮,转换所有n的倍数的灯泡开关,找出有几盏灯泡是开着的

算法分析

灯泡开始是关闭状态。奇数次轮以后,为开启状态;偶数次轮后为关闭状态。因此本题也就是转化为寻找小于等于n的数的因数的个数为奇数的情况。只有平方数的因数为奇数个
例如:6的因数为1,6,2,3;而9的因数为1,9,3;

Java代码

public class Solution {
    public int bulbSwitch(int n) {
        if(n <= 0) return 0;
        
        return (int)Math.sqrt(n);//本题最后转化为求小于等于n的平方数的个数
    }
}

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,900评论 0 23
  • 每个人的生命中,朋友大概都是很重要的一部分吧!我们那么在乎朋友,却又不可避免的会伤害到朋友,同时也会被朋友伤害。 ...
    小小兰Cassie阅读 428评论 0 0
  • 1.进程 系统中正在运行的应用程序每个进程之间是相互独立的,运行在各自独有且受保护的内存中 2.线程 1.进程是不...
    GSChan阅读 400评论 0 2
  • Java基本数据类型 程序设计语言本质上是一种语言,它是人与计算机进行交流的媒介,使用程序语言编写程序的目的是让计...
    ZmlLucky阅读 719评论 1 1
  • 昨晚终于把过去漏掉三天日间记录补上;本来想整理下《万能钥匙》观后感,但看了别人的影评之后反倒无从下手了,想通过思维...
    二石兄阅读 210评论 0 1