[LeetCode]题解(python):069-Sqrt(x)

题目来源:

  https://leetcode.com/problems/sqrtx/


 

题意分析:

  实现一个整型的开根。


 

题目思路:

  利用牛顿迭代法可以求解。首先讲数据类型转成浮点数,然后选取初始值为n/2,然后用牛顿迭代,直到迭代结果相差小于1.0,最后将浮点数转回整型。


 

代码(Python):

  

 1 class Solution(object):
 2     def mySqrt(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         if x == 0:
 8             return 0
 9         ans = float(x)
10         newx = ans
11         ans /= 2
12         while True:
13             tmp = ans
14             ans = (ans + newx / ans) / 2.0;
15             if abs(tmp - ans) < 1:
16                 break
17         return int(ans)
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/5045512.html

posted @ 2015-12-14 15:57  Ry_Chen  阅读(297)  评论(0编辑  收藏  举报