Skip to content

Commit 1d3dba3

Browse files
committed
another solution for "Bulb Switcher"
1 parent 41134d7 commit 1d3dba3

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

algorithms/cpp/bulbSwitcher/bulbSwitcher.cpp

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/bulb-switcher/
2-
// Author : Calinescu Valentin
2+
// Author : Calinescu Valentin, Hao Chen
33
// Date : 2015-12-28
44

55
/***************************************************************************************
@@ -21,6 +21,42 @@
2121
* So you should return 1, because there is only one bulb is on.
2222
*
2323
***************************************************************************************/
24+
25+
/* Solution
26+
* --------
27+
*
28+
* We know,
29+
* - if a bulb can be switched to ON eventually, it must be switched by ODD times
30+
* - Otherwise, if a bulb has been switched by EVEN times, it will be OFF eventually.
31+
* So,
32+
* - If bulb `i` ends up ON if and only if `i` has an ODD numbers of divisors.
33+
* And we know,
34+
* - the divisors come in pairs. for example:
35+
* 12 - [1,12] [2,6] [3,4] [6,2] [12,1] (the 12th bulb would be switched by 1,2,3,4,6,12)
36+
* - the pairs means almost all of the numbers are switched by EVEN times.
37+
*
38+
* But we have a special case - square numbers
39+
* - A square number must have a divisors pair with same number. such as 4 - [2,2], 9 - [3,3]
40+
* - So, a square number has a ODD numbers of divisors.
41+
*
42+
* At last, we figure out the solution is:
43+
*
44+
* Count the number of the squre numbers!!
45+
*/
46+
47+
class Solution {
48+
public:
49+
int bulbSwitch(int n) {
50+
int cnt = 0;
51+
for (int i=1; i*i<=n; i++) {
52+
cnt++;
53+
}
54+
return cnt;
55+
}
56+
};
57+
58+
59+
2460
/*
2561
* Solution 1 - O(1)
2662
* =========

0 commit comments

Comments
 (0)