美文网首页LeetCode
LeetCode刷题之Sqrt

LeetCode刷题之Sqrt

作者: JRTx | 来源:发表于2017-08-24 19:35 被阅读0次
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;
}

相关文章

网友评论

    本文标题:LeetCode刷题之Sqrt

    本文链接:https://www.haomeiwen.com/subject/ssaedxtx.html