We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8adba39 commit b591d36Copy full SHA for b591d36
cpp-leetcode/leetcode279-perfect-squares_math-method.cpp
@@ -0,0 +1,40 @@
1
+#include<iostream>
2
+#include<cmath>
3
+using namespace std;
4
+
5
+/* 解题思路见题解 <https://leetcode-cn.com/problems/perfect-squares/solution/shu-xue-fa-bu-shi-yong-dong-tai-gui-hua-ddm33/> */
6
+class Solution {
7
+public:
8
+ int numSquares(int n) {
9
+ while (n % 4 == 0)
10
+ n /= 4;
11
12
+ if (n % 8 == 7)
13
+ return 4; // (path 1)
14
15
+ for (int i = 0; i * i <= n; i++)
16
+ {
17
+ int r = (int)sqrt(n - i * i);
18
+ if (i * i + r * r == n)
19
20
+ if (i == 0 || r == 0)
21
+ return 1; // (path 2)
22
23
+ return 2; // (path 3)
24
+ }
25
26
27
+ return 3; // (path 4)
28
29
+};
30
31
+// Test
32
+int main()
33
+{
34
+ Solution sol;
35
+ int k = 12;
36
+ int res = sol.numSquares(k);
37
+ cout << res << endl;
38
39
+ return 0;
40
+}
0 commit comments