码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Bulb Switcher

时间:2015-12-20 17:23:11      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

Bulb Switcher

There are n bulbs 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). For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

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.

https://leetcode.com/problems/bulb-switcher/

 

 


 

 

题目意思是一开始灯泡都是关的,从2开始的第n轮就开关n倍数的灯泡,打开原来关的灯泡,关上开着的。

一看就是数学题,搞个数组去模拟肯定TLE,有大数,需要找规律。

像我这种数学拙计的选手,就是死算,从1推到10应该就能看出规律了,所有剩下的灯泡都是平方数1, 4, 9。

看看大神的解释:

https://leetcode.com/discuss/75014/math-solution

我的理解是,比如12可以拆成1和12, 2和6, 3和4,他们两两之间碰不到,或者碰到奇数次,最后是关的。

而像10, 11这种只可能碰到一次,最后是关的。

如果是平方数比如9,3的时候关了,9的时候又会打开,所以最后是打开的。

 

1 /**
2  * @param {number} n
3  * @return {number}
4  */
5 var bulbSwitch = function(n) {
6     return parseInt(Math.sqrt(n));
7 };

 

 

 

 

 

[LeetCode][JavaScript]Bulb Switcher

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/5061144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!