LeetCode:319. Bulb Switcher(C版本)

来源:互联网 发布:淘宝号怎样快速升心 编辑:程序博客网 时间:2024/06/04 00:56

题目链接:

这里写链接内容


题目内容:

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 ith round, you toggle every i bulb. 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.

题目解释:

有一堆n个灯泡,我们将进行n轮操作,初始的时候,所有灯泡都是关着的,然后第一轮我们打开所有灯泡。第二轮灯泡两两一组,关闭一组中的第二个灯泡。第三轮每三个灯泡一组,如果第三个灯泡开着,那么我们就关闭它,如果关着,我们就打开它。对于第i轮,每i个灯泡一组,然后对每一组的第i个灯泡采取跟第3轮相同的操作。当进行到最后一轮时,我们只对最后一个灯泡进行打开或者关闭操作。程序要求返回n轮过后,亮着的灯泡数目。
题目中给了一个例子:
假设我们给定灯泡的操作轮数为3,那么我们就将进行3轮操作,

  1. [off, off, off]最开始关闭所有灯泡。
  2. [on, on, on]第一轮过后,打开所有灯泡。
  3. [on, off, on]第二轮过后,打开每一组的第二个灯泡。
  4. [on, off, off]第三轮,仅对最后一个灯泡进行toggle操作。

这时,开着的灯泡还剩下一个,所以我们返回1.


解题方案:

这个题目描述的华丽胡哨的,然而越是这样的题目越可能是一个比较简单的数学公式就可以解决的,属于找规律的题目。
对于一第K个灯泡,如果K有偶数个因子的话,它在最后就是off状态,比如3,5,等等,如果K有奇数个因子的话,它在最后就是on状态,比如1,4,9等等,有奇数个因子的数就是那些完全平方数(即能开方的数)。所以我们只要统计小于等于n的完全平方数的个数即可,对n开方即可等到


AC代码:

这个程序的代码十分简单。

int bulbSwitch(int n){  return sqrt(n);}
0 0
原创粉丝点击