Leetcode: Bulb Switcher_leetcode

Source: Internet
Author: User
Tags square root

There are n bulbs that are initially off. You have the turn on all the bulbs. Then, turn off every second bulb. On the third round, your toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every I bulb. For the nth round, you are toggle the last bulb. Find how to many bulbs are on after n rounds.

Example:

Given n = 3.

At the three bulbs are [out, off, off].
After the-round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, out, on].
After third round, the three bulbs are [on, out, off].

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

A [1,n] bulb is in a closed state to determine how many light bulbs are on when the nth wheel is on. In the first round, light all the bulbs, and the second round light the bulbs of all multiples of 2, and the third round, light the bulbs of all multiples of 3;

Solution: The bulb after the toss of the N round, in the bright state, indicates that the button of the bulb is pressed for an odd number of times, such as the first light bulb, if its button is pressed, then I must be a number of decomposition factors in [1,n], and for a number its factorization factor generally appears in pairs, such as 12:1-12, 2-6,3-4, unless the number can open the root, such as 36. For the first case, the bulb must be pressed even several times, and the second is odd several times. So to n open the square root can know how many numbers have been hit the odd number of times.

Code:

public class Solution {public
    int bulbswitch (int n) {return
        (int) (MATH.SQRT (n));
    }

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.