【算法-数学】灯泡开关

LeetCode 319. Bulb Switcher
一开始有n个灯泡关闭。第1轮,打开所有的灯泡;第2轮,每两个灯泡关闭一次;第3轮,每三个灯泡切换一次开关(如过打开则关闭,如果关闭则打开);第n轮,只切换最后一个灯泡的开关。求n轮过后还有多少个灯亮着。

示例:
输入:3
输出:1
解释:状态0表示灯泡关闭,1表示开启。
初始时,灯泡状态[0 0 0]
第1轮后,灯泡状态[1 1 1]
第2轮后,灯泡状态[1 0 1]
第3轮后,灯泡状态[1 0 0]

public class BulbSwitcher {
    
    
	//n个灯泡开关n轮,最后满足开启的灯泡个数满足完全平方数
    public static int bulbSwitcher(int n) {
    
    
        if (n < 2) {
    
    
            return n;
        }
        return (int) Math.sqrt(n);
    }
}

猜你喜欢

转载自blog.csdn.net/runewbie/article/details/107053399