LeetCode 319 ——Bulb Switcher——————【数学技巧】

时间:2021-05-31 09:00:59

319. Bulb Switcher

My Submissions

QuestionEditorial Solution
Total Accepted: 15915 Total Submissions: 39596 Difficulty: Medium

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个灯泡编号1~n,开始都是关着的,在第i轮,将编号为i的倍数的灯切换状态(开->关、关->开)。问你n轮后灯亮着的有多少个。 解题思路:想到了对于每个灯泡,如果它的因子个数为奇数,那么它必然会是开着的。但是这还不是最机智的做法,更近一步去思考,你会发现,x的因子满足 p*q == x,所以进而转化成只要是完全平方数,那么就会是亮着的。
class Solution {
public:
int bulbSwitch(int n) {
int ret = 0;
for(int i = 1; i*i <= n; i++){
ret++;
}
return 0;
}
};