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.
方法1:
思路:
只有当 i 是平方数的时候才会最后停留在on的状态。以n = 36 举例来说,他的除数有(1, 36), (2, 18), (3 , 12), (4, 9), (6, 6), (9, 4), (12, 3), (18, 2), (36, 1),其他的除数都会被一对一对的on->off,除了6。也就是说,只有平方数才会被switch奇数次。
class Solution {
public:
int bulbSwitch(int n) {
int result = 0;
for (int i = 1; i * i <= n; i++) {
result++;
}
return result;
}
};