Skip to content

Commit 80793be

Browse files
committed
added 0069_sqrt.py
1 parent 0dbe503 commit 80793be

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

problems/easy/0069_sqrt.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Given a non-negative integer x, compute and return the
3+
square root of x.
4+
5+
Since the return type is an integer, the decimal digits
6+
are truncated, and only the integer part of the result
7+
is returned.
8+
9+
Note: You are not allowed to use any built-in exponent
10+
function or operator, such as pow(x, 0.5) or x ** 0.5.
11+
12+
Example 1:
13+
Input: x = 4
14+
Output: 2
15+
16+
Example 2:
17+
Input: x = 8
18+
Output: 2
19+
Explanation: The square root of 8 is 2.82842..., and
20+
since the decimal part is truncated, 2 is returned.
21+
22+
Constraints:
23+
* 0 <= x <= 2^31 - 1
24+
"""
25+
26+
class Solution:
27+
# O(log n) solution using Newton's algorithm
28+
#def mySqrt(self, x: int) -> int:
29+
# ap = x
30+
#
31+
# while abs(x - ap * ap) >= 1:
32+
# ap = (ap + (x / ap)) / 2
33+
#
34+
# return int(ap)
35+
36+
# O(log n) solution
37+
def mySqrt(self, x: int) -> int:
38+
half = x // 2
39+
40+
while half * half > x:
41+
half = half // 2
42+
43+
if half * half == x:
44+
return half
45+
46+
while half * half < x:
47+
half += 1
48+
49+
if half * half == x:
50+
return half
51+
52+
return half - 1

0 commit comments

Comments
 (0)