forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfectSquares_279.java
More file actions
43 lines (35 loc) · 1.07 KB
/
PerfectSquares_279.java
File metadata and controls
43 lines (35 loc) · 1.07 KB
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
package LeetCode;/**
* @Classname PerfectSquares_279
* @Description 表示成为平方的和
* 解决方案:任何一个正整数可以被表示为最多四个整数的平方和
* @Date 19-5-21 下午1:51
* @Created by mao<[email protected]>
*/
public class PerfectSquares_279 {
public int numSquares(int n) {
if (n == 0) return 0;
if (isSquare(n)) return 1;
if (isSumOfFourIntegers(n)) return 4;
if (isSumOfSquares(n)) return 2;
return 3;
}
private boolean isSquare(int n) {
int squareRoot = squareRoot(n);
return squareRoot * squareRoot == n;
}
private int squareRoot(int n) {
return (int) Math.sqrt(n);
}
// Values of the form 4^n(8k+7) are the sum of 4 integers.
private boolean isSumOfFourIntegers(int n) {
while (n % 4 == 0) n /= 4;
return n % 8 == 7;
}
// O(sqrt(n))
private boolean isSumOfSquares(int n) {
for (int i = 1; i <= squareRoot(n); i++) {
if (isSquare(n - (i * i))) return true;
}
return false;
}
}