leetcode-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 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 次之后,留下的小于等于 n 的平方数,为什么呢,比如我们考虑第 m 个灯泡什么时候改变,如 m 等于16,16的因子数有1,2,4,8,16,我们把这个数字分组,可分成(1, 16), (2, 8), (4),对于平方数,总是会留下一个单独的,以1分隔时,灯打开了,以16分隔时灯又免了,但最终会留下一个单独的,使灯打开,因此留下的都是平方数,程序只需返回小于等于 n 的平方数的个数。

解决方案1(C++)


1
2
3
4
5
6
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};

相关问题


题目来源