【LeetCode】69. Sqrt(x)

問題描述

https://leetcode.com/problems/sqrtx/#/description

Implement int sqrt(int x).

Compute and return the square root of x.

算法

使用折半查找即可,但要注意整型溢出

代碼

public int mySqrt(int x) {
    int left = 1, right = x;            
    while(left<=right) {
        int mid = left + (right-left)/2;// 不能使用(right+left),因爲有可能整數溢出
        if(mid <= x/mid) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return left-1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章