Problem Description:
If it s off or turning off if it's on). For the nth round, you are toggle the last bulb. Find How many bulbs is on after n rounds.
Problem Analysis:
/*** * There is n bulbs that is initially off. * You first turn 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 are toggle the last bulb. Find How many bulbs is on after n rounds. * * First, find the rule from a given topic: that is, when I is any number between 1 and n, flip k = The state of the bulb on the RI position. * After the N-wheel, how many lights are still open? * Second, the most intuitive method is the poor lifting method: a round of the Traverse, but when n is large, time complexity is too large. * Third, to find the law: * If there are 5 lights, after 5 rounds of flipping, and finally only the 1th and 4th is lit, it may be analyzed, whether there is any law? * Start: 5 lights all off * 1 = (1 times) flipped, final on * 2 = (), (2,1) 2 times flipped, final Off * 3 = (1,3), (3,1) 2 flips, final off * 4 = (1,4), (2,2), (4,1) 3 times rollover, final on * 5 = (1,5), (5,1) 2 Flips, final off * * can be seen, the final on the lamp location is the square number *@authorAdmin **/
Code:The number of squares between 1 and N is: sqrt (n) rounded down .
// How many lights are on after returning to the N-wheel Public Static int bulbswitch (int n) { if(n <= 0) return 0 ; int num = (int// computes the square root of N, double casts to int type, which is rounded down.) System.out.println (num); return num; }
Bulb Switcher (Leetcode Java)