LeetCode:Bulb Switcher

来源:互联网 发布:nagios源码 编辑:程序博客网 时间:2024/06/05 10:31

题目描述:

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.

思路:

这是一个类似脑筋急转弯的题目。

题目翻译成数学问题就是:整数1-n中有奇数个约数的数有多少个。

如:

1的约数:1。有1个。

2的约数:1、2。有2个。

3的约数:1、3。有2个。

4的约数:1、2、4。有3个。

5的约数:1、5。有2个。

6的约数:1、2、3、6。有4个。

7的约数:1、7。有2个。

8的约数:1、2、4、8。有4个。

9的约数:1、3、9。有3个。

从中发现规律,1、4、9有奇数个约数,它们都是某个数的平方。这些编号的灯会亮着。

只要统计1-n中有多少个是一个数的平方就可以了。

这些数是,1^2,2^2,3^3,……,sqrt(n)^2.

一共是sqrt(n)个。

代码:

class Solution {public:   int bulbSwitch(int n){return (int)sqrt(n);}};


0 0