"Leetcode from zero single brush" Bulb switcher

Source: Internet
Author: User

Topic:

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 then-th round, you are only toggle the last bulb. Find How many bulbs is on afterN rounds.

Example:

N [Off, off, off] [on, on, on] [on, Off, on] [on, off, off]. So you should return 1, because there are only one bulb are on.

Answer:

We know that whenever a light bulb changes state, that is, toggle, it is because it appears on the integer multiples of a number.

For the 1th bulb: 1*1, it will change 1 times, i.e. off-"on

For the 2nd bulb: 1*2,2*1, it will change 2 times, i.e. off-"on-" off

For the 3rd bulb: 1*3,3*1, it will change 2 times, i.e. off-"on-" off

For the 4th bulb: 1*4,2*2,4*1, it will change 3 times, i.e. off-"on-" off-"on

......

Will find that whenever I find an integer multiple of a number, I always find an integer multiple of symmetry , for example 1*2, there will certainly be a 2*1. The only exception appears on the square number, for example 4 = 2*2, with only one integer multiple.

Each time as an even number of integers, the final bulb will revert to off, and the final bulb will be switched on only as an odd number of times.

That is, the number of light bulbs that are finally lit is determined by the maximum number of squares less than. The code is simple:

Class Solution {public:    int bulbswitch (int n) {        return (int) sqrt (n);    }};

"Leetcode from zero single brush" 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.