• LeetCode 319. Bulb Switcher


    原题链接在这里:https://leetcode.com/problems/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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

    Example:

    Input: 3
    Output: 1 
    Explanation: 
    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,初始的时候灯都是灭的,让你进行进行开关灯。第一轮的时候把1的倍数反转(原来关就开,原来开就关),第二轮把2的倍数反转,以此类推到第n轮。

    求最后灯打开的个数.

    对于素数,那么它仅有1和它本身,最后一定是关掉的。

    对一普通的,一定是关掉的,因子成对出现

    对于完全平方数,因为有一个倍数不成对出现,所以一定是打开的。比如4 => 1,4开; 2关

    所以本题就是求1~n有几个完全平方数。

    直接返回sqrt(n).

    Time Complexity: O(1). Space: O(1).

    AC Java:

    1 public class Solution {
    2     public int bulbSwitch(int n) {
    3         return (int)Math.sqrt(n);
    4     }
    5 }

    Reference: http://blog.csdn.net/murmured/article/details/50363720

  • 相关阅读:
    ajax代码及简单封装
    web开发中不同设备浏览器的区分
    JS实现带复选框的下拉菜单
    常用浏览器的编码设置
    PHP实现实现数字补零格式化
    Linux杂碎2/SHELL
    OS
    Linux sudoers
    代理缓存服务器squid
    es6
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5153558.html
Copyright © 2020-2023  润新知