LeetCode刷题之Sqrt

Problem

Implement int sqrt(int x).

Compute and return the square root of x.

My Solution
class Solution {
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        for (int i = 1; i <= x / 2 + 1; i++) {
            if (x / i == i) {
                return i;
            } else if (x / i < i) {
                return i - 1;
            }
        }
        return x;
    }
}
Great Solution
public int mySqrt(int x) {
    if (x == 0) return 0;
    long i = x;
    while(i > x / i)  
        i = (i + x / i) / 2;            
    return (int)i;
}
    原文作者:Gandalf0
    原文地址: https://www.jianshu.com/p/f3debeed0ca3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞