leetcode69. Sqrt(x)

xiaoxiao2021-02-27  509

一。二叉树:

1.确定左右界

2.算mid

3.根据条件调整左右键

4.重复2-3

5根据条件返回mid

public int sqrt(int x) { if (x == 0) return 0; int left = 1, right = Integer.MAX_VALUE; while (true) { int mid = left + (right - left)/2; if (mid > x/mid) { right = mid - 1; } else { if (mid + 1 > x/(mid + 1)) return mid; left = mid + 1; } } } https://leetcode.com/problems/sqrtx/#/solutions

二:简写

 r = x     while r*r > x:         r = (r + x/r) / 2     return r

long r = x; while (r*r > x) r = (r + x/r) / 2; return (int) r; https://leetcode.com/problems/sqrtx/#/solutions

转载请注明原文地址: https://www.6miu.com/read-2466.html

最新回复(0)