Leetcode 319:bulb Switcher

Source: Internet
Author: User

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 i-th round, you toggle every i bulb. For the n-th round, you are only toggle the last bulb. Find How many bulbs is on after N rounds.

Example:

N

So you should return 1, because there are only one bulb are on.

Test instructions

Open n Bulbs;

The first round, each of the I bulb reversal; (2<=i<=n)

The number of light bulbs to be last lit;

Ideas:

General timeout;

Law:

N:1 2 3 4 5 6 7 8 9 10 11

Ans:1 1 1 2 2 2 2 2 3 3 3

1 class Solution {2public:3     int bulbswitch (int  n) {4         return  sqrt (n); 5     }6 };
View Code

--------------Update----------------

Behind the principle:

When the first wheel reverses, the light bulb State of the multiple position of I is reversed;

For the bulb I, each time to its factor will be reversed;

And the factor is usually paired, and the state is unchanged after two times reversal;

The only exception is that the two factors are the same, then only one time is reversed;

At this point, the number is the square number;

For n, the actual number of squares to be asked;

So sqrt (n).

Leetcode 319:bulb Switcher

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.