public class Solution { public int MySqrt(int x) { long r = x; while (r * r > x) r = (r + x / r) / 2; return (int)r; } }
https://leetcode.com/problems/sqrtx/#/description
补充一个python的实现:
1 class Solution: 2 def mySqrt(self, x: int) -> int: 3 r = x 4 while r * r > x: 5 r = (r + x // r) // 2 6 return int(r)
使用内置函数:
1 class Solution: 2 def mySqrt(self, x: int) -> int: 3 return int(x ** 0.5)
Java的内置函数:
1 class Solution { 2 public int mySqrt(int x) { 3 double xx = Double.valueOf(x); 4 return (int)Math.sqrt(xx); 5 } 6 }