forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
51 lines (40 loc) · 999 Bytes
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// Source : https://leetcode.com/problems/bulb-switcher/description/
/// Author : liuyubobobo
/// Time : 2017-12-01
#include <iostream>
#include <cassert>
using namespace std;
/// For every number, see whether the divisor number is odd
/// Time Complexity: O(n*sqrt(n))
/// Space Complexity: O(1)
///
/// Time Limit Exceed!!!
class Solution {
public:
int bulbSwitch(int n) {
assert(n >= 0);
if(n <= 1)
return n;
int count = 1;
for(int i = 2 ; i <= n ; i ++)
if(divisorNumber(i) % 2 == 1)
count += 1;
return count;
}
private:
int divisorNumber(int x){
int ret = 0;
for(int i = 1 ; i * i <= x ; i ++)
if(x % i == 0){
ret += 1;
if(x / i != i)
ret += 1;
}
return ret;
}
};
int main() {
cout << Solution().bulbSwitch(2) << endl;
cout << Solution().bulbSwitch(3) << endl;
return 0;
}