LeetCode Bulb Switcher 319, leetcodeswitcher

Source: Internet
Author: User

LeetCode Bulb Switcher 319, leetcodeswitcher

Change the light bulb color

There areNBulbs that are initially off. you first turn on all 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 ). forNTh round, you only toggle the last bulb. Find how many bulbs are on afterNRounds.

Example:

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

Coding

public int bulbSwitch(int n){        int[] arrN = new int[n];        int count = 0;        for (int i = 0; i < arrN.length; i++) {            arrN[i] =0;        }        for (int i = 0; i < arrN.length; i++) {            for (int j = 0; j < arrN.length;j++ ) {                if(i==0){                    arrN[j] = 1;//                    j++;                }else{                    int k = i+1;                    if((j+1)%k==0){arrN[j]=(arrN[j]==1?0:1);}//                    j=j+i;                }            }        }                for (int i = 0; i < arrN.length; i++) {            if (arrN[i]==1) {                count++;            }        }        return count;    }

 

Running Timeout:

The color change of the light bulb only exists in its own factor.

1. prime number, only 1 and yourself.

2. Common number, which is paired with a factor.

3. the light bulb will not be extinguished only when the bulb is fully lit for an odd number of times.

This question is converted to the number of full counters !!!

For example, 3 --> 3

1 public static int bulbSwitch(int n){2     return (int)Math.sqrt(n);3 }

 

Related Article

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.