forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAC_math_logn.cpp
More file actions
45 lines (35 loc) · 765 Bytes
/
Copy pathAC_math_logn.cpp
File metadata and controls
45 lines (35 loc) · 765 Bytes
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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_math_logn.cpp
* Create Date: 2015-10-26 13:46:45
* Descripton:
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class Solution {
private:
bool isSquare(int n) {
int root = (int)sqrt(n);
return root * root == n;
}
public:
int numSquares(int n) {
if (isSquare(n))
return 1;
// 4^k*(8*m + 7) : return 4
while ((n & 3) == 0)
n >>= 2;
if ((n & 7) == 7)
return 4;
// check 2
int root = (int)sqrt(n);
for (int i = 1; i <= root; ++i)
if (isSquare(n - i * i))
return 2;
return 3;
}
};
int main() {
return 0;
}