topic:
Given a non-negative integer x, compute and return the arithmetic square root of x .
Since the return type is an integer, only the integer part of the result is retained , and the decimal part will be rounded off .
Note : Any built-in exponential functions and operators are not allowed, such as pow(x, 0.5) or x ** 0.5.
Example 1:
输入:x = 4
输出:2
Example 2:
输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
answer:
Instead of arithmetic square roots, we use the pocket calculator algorithm
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:return 0
ans = int(math.exp(0.5 * math.log(x)))
return ans + 1 if (ans + 1) ** 2 <= x else ans