Bulb Switcher (Leetcode Java)

Source: Internet
Author: User
Tags rounds square root

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.