[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);
    }
}
原文地址:https://www.cnblogs.com/Victor-Han/p/5157428.html