zoukankan      html  css  js  c++  java
  • [LeetCode 319] Bulb Switcher

    Question

    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.

    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.

    Explanation

    A bulb ends up on iff it is switched an odd number of times.
    A bulb is switched an odd number of times iff it has an odd number of divisors.
    The normal number has an even number of divisors.
    The square number has an odd number of divisors. That is because it has two same divisors.
    We should calculate how many square numbers are less than or equal to n.

    Code

    public class Solution {
        public int bulbSwitch(int n) {
            return (int)Math.sqrt(n);
        }
    }
    
  • 相关阅读:
    寒假自学1.18
    寒假自学笔记1.17
    寒假自学1.16
    寒假自学1.15
    寒假自学1.14
    寒假自学1.13
    寒假自学1.12
    CSS position 属性
    node 获取客户端请求 服务器响应客户端 页面显示客户端想要的格式
    使用 npm 安 装node_modules 总是提示报错
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5157428.html
Copyright © 2011-2022 走看看