原題地址:https://oj.leetcode.com/problems/sqrtx/
題意:
Implement int sqrt(int x).
Compute and return the square root of x.
解題思路:實現開平方函數。這里要注意的一點是返回的時一個整數。通過這一點我們可以看出,很有可能是使用二分查找來解決問題的。這里要注意折半查找起點和終點的設置。起點i=1;終點j=x/2+1;因為在(x/2+1)^2 > x,所以我們將折半查找的終點設為x/2+1。
代碼:
class Solution: # @param x, an integer # @return an integer def sqrt(self, x): if x == 0: return 0 i = 1; j = x / 2 + 1 while( i <= j ): center = ( i + j ) / 2 if center ** 2 == x: return center elif center ** 2 > x: j = center - 1 else: i = center + 1 return j
