319. 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 i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

Input: 3
Output: 1 
Explanation: 
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.

Solution 1:

中规中矩地来,按照要求放入过程走。

int bulbSwitch(int n)
{
	if (n == 0 || n == 1)return n;
	vector<int> status(n, 1);
	int turn_on = n;
	for (int i = 2; i < n; i++)
	{
		for (int begin = i - 1; begin < n; begin = begin + i)
		{
			turn_on -= status[begin];
			turn_on += (status[begin] + 1) % 2;
			status[begin] = (status[begin] + 1) % 2;
		}
	}
	if (status[n - 1] == 0)turn_on++;
	else turn_on--;
	return turn_on;
}

Solution 2:

用Solution 1中的方法试了几次之后发现结果居然是sqrt(n)。细究原因,发现每一个灯只有两种状态,并不是每一轮都能翻转此灯的状态,只有是某灯的因子轮时才能解除到此灯,比如说,第25个灯,第1,25轮可以接触到,第2轮时不能接触到此灯,第3,4轮均不行,但是第5轮可以。同样的第26个灯,第1,26,2,13轮才能接触到此灯,所以当某灯的因子个数为偶数时,其最终的状态为关,因子个数为奇数时,其最终状态为开,因子都是成对存在的,只有平方数(4,16,15...)才拥有奇数个因子,所以最终所有的奇数位上的灯都是开着的,所以我们只需要统计在所有的灯中有多少个平方数。就能得到结果sqrt(n)。

int bulbSwitch(int n)
{
    return sqrt(n);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值