Skip to content

Commit 737c345

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
surtax.py
1 parent e076cf2 commit 737c345

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

problems/sqrtx.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
The ans must be in between 0 and `x`.
3+
So we set the lower bound `l` to 0. The upper bound `r` to `x`.
4+
The answer will always between `l` and `r`.
5+
For every iteration, if `l`, `m`, `r` are not answer, we adjust the `l` or `r`.
6+
Until we find the answer
7+
"""
8+
class Solution(object):
9+
def mySqrt(self, x):
10+
def isAns(a):
11+
if a**2<=x and (a+1)**2>x:
12+
return True
13+
return False
14+
15+
l = 0
16+
r = x
17+
while True:
18+
m = (l+r)/2
19+
if isAns(l): return l
20+
if isAns(m): return m
21+
if isAns(r): return r
22+
23+
if m**2<x:
24+
l = m+1
25+
else:
26+
r = m-1
27+
return -1

0 commit comments

Comments
 (0)