319. Bulb Switcher
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 1:
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.
题目地址:Bulb Switcher
题意:
给定n,共有n盏灯,初始的时候灯都是灭的,然后进行n轮开关灯,规则是第i轮内要将i的倍数的灯都反转。求最后灯打开的个数。
思路:
对于第j轮的第
i
盏灯,只有当
初始的时候灯都是灭的,所以当i有偶数个因子时,最后第i盏灯就是灭的,反之则是打开的。
对于素数,因子必然为两个(1和自身)。回忆下求某数因子个数的算法:
for(int i = sqrt(n);i > 0;--i){
if(n%i == 0){
if(i*i == n) ans++;
else ans += 2;
}
}
就是说只有当某数是平方数时,因子个数才为奇数,灯最后才是打开的。答案等于[0,n]内平方数的个数floor(sqrt(n))。
C++
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
C++知识点
隐式类型转换:
当调用函数时,函数返回值和形参会发生隐式的强制类型转换。
经验:
当没有思路时,找几个简单的数据模拟,观察输入、输出值的规律,往往有助于找到新的解题思路。