zoukankan      html  css  js  c++  java
  • Bulb Switcher (leetcode java)

    问题描述:

    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 nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

    问题分析:

    /**
     * 
     * 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 nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
     * 
     * 一、从给定的题目中找到规律:就是,当 i 为  1 到 n之间的任何数时,翻转 k = ri 位置上灯泡的状态。
     * 求n轮之后,还有几盏灯是开着的?
     * 二、最直观的方法是穷举法:一轮轮的遍历,但是,当n很大时,时间复杂度太大。
     * 三、找规律:
     * 若起初有5盏灯,经过5轮翻转后,最终只有第1盏和第4盏是亮着的,不妨分析下,这里面是否有什么规律?
     * 起始:5盏灯全部为 off
     * 1 = (1,1)                                       1次翻转,最终on
     * 2 = (1,2),(2,1)                      2次翻转,最终off
     * 3 = (1,3),(3,1)                      2次翻转,最终off
     * 4 = (1,4),(2,2),(4,1)    3次翻转,最终on
     * 5 = (1,5),(5,1)                      2次翻转,最终off
     * 
     * 可以看出,最终为on的灯所在位置都是平方数
     * @author admin
     *
     */

    代码:1到n之间 平方数的个数 为: sqrt(n) 向下取整

    //返回n轮之后,有多少盏灯是开着的
        public static int bulbSwitch(int n){
            if(n <= 0)
                return 0;
            int num = (int)Math.sqrt(n); //求n的平方根,double强制转换为int类型,即为向下取整。
            
            System.out.println(num);
            
            return num;
        }
  • 相关阅读:
    设备树(Device Tree)
    深度Linux Deepin系统安装教程使用体验
    Qt Creator的安装与Qt交叉编译的配置
    移植tslib和Qt5.6到三星s5pv210开发板
    Linux下读取RFID卡号(C串口编程)
    如何移植openwrt系统
    如何在Qt Creator中添加库文件和头文件目录
    Qt Creator中如何选择某个子项目为启动项目
    QT中子目录调用另一个子目录
    在Qt项目中如何添加一个已有的项目作为子项目
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5162425.html
Copyright © 2011-2022 走看看