File tree 1 file changed +83
-0
lines changed
1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
3
+ Example 1:
4
+
5
+ Input: c = 5
6
+ Output: true
7
+ Explanation: 1 * 1 + 2 * 2 = 5
8
+ Example 2:
9
+
10
+ Input: c = 3
11
+ Output: false
12
+ Example 3:
13
+
14
+ Input: c = 4
15
+ Output: true
16
+ Example 4:
17
+
18
+ Input: c = 2
19
+ Output: true
20
+ Example 5:
21
+
22
+ Input: c = 1
23
+ Output: true
24
+
25
+ Constraints:
26
+
27
+ 0 <= c <= 231 - 1
28
+
29
+ """
30
+
31
+
32
+ class Solution :
33
+ def findsquarerootwithBST (self ,c ):
34
+ l = 0
35
+ r = c
36
+
37
+ while l < r :
38
+ m = (l + r ) // 2
39
+ if m == l or m == r :
40
+ if l ** 2 < c :
41
+ return l
42
+ if r ** 2 < c :
43
+ return r
44
+
45
+
46
+ if m ** 2 > c :
47
+ r = m
48
+ elif m * m < c :
49
+ l = m
50
+ else :
51
+ if m ** 2 == c :
52
+ return m
53
+
54
+
55
+
56
+
57
+
58
+ def judgeSquareSum (self , c : int ) -> bool :
59
+ if c == 0 or c == 1 :
60
+ return True
61
+
62
+
63
+ a = self .findsquarerootwithBST (c )
64
+
65
+
66
+ i ,j = 0 ,a
67
+ while i <= j :
68
+ r = i ** 2 + j ** 2
69
+
70
+ if r == c :
71
+ return True
72
+ elif r < c :
73
+ i += 1
74
+ else :
75
+ j -= 1
76
+ return False
77
+
78
+
79
+
80
+
81
+
82
+
83
+
You can’t perform that action at this time.
0 commit comments