[LeetCode] Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

牛顿迭代

 1 class Solution {
 2 public:
 3     int sqrt(int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         double ans = x;
 7         
 8         while(abs(ans * ans - x) > 0.0001)
 9         {
10             ans = (ans + x / ans) / 2;
11         }
12         
13         return (int)ans;
14     }
15 };
posted @ 2012-11-18 11:45  chkkch  阅读(1507)  评论(1编辑  收藏  举报