Leetcode 319. Bulb switcher

Source: Internet
Author: User

This is a very ingenious topic, the site is called brain teaser, meaning that the code will be very brief description (is to tease you to play:)), the topic is as follows:

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

Example:

 given  n  = 3.  
at first, the three bulbs is [off, off, off]. After first round, the three bulbs is [on, on,]. After second round, the three bulbs is [on, off, on]. After third round, the three bulbs is [on, off, off].
so you should return 1, because there are only one bulb are on.

first: 1x1 only in this case, so all the bulbs are off--and on
second: 2x1 1*2 that is to say there will be two switch, one is 1 for the interval switch, and the other is 2 is the interval switch,off->on-->off
third: 1x3 3x1,off-->on-->off
,,,,

and so on, we find that a*b always has a b*a counterpart, that is, an even number of switch, so that the off or off,on or on, that is, to remain unchanged, in addition to a situation, is 3x3 this, if the sqrt (interval) is an integer, Indicates that there is an odd number of switch, the state changes will occur, then we can now consider this problem is very simple, because at the beginning all the bulbs are extinguished, so we just need to look for 1. Less than n,2. And sqrt is the number of integers. The answer is obviously sqrt (n)

Code:
class Solution {public:    int bulbswitch (int  n) {        return (int) 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.