leetcode 69.x的平方根(Java 二分查找 easy)

https://leetcode-cn.com/problems/sqrtx/函數

實現int sqrt(int x)函數,給定一個數字,求sqrt(x)而且保留整數部分。spa

 

二分查找,令l=1,h=x,判斷l<=h,當跳出循環時,即sqrt(x)不爲整數時,return h,由於跳出循環時l>h,本題要求只保留整數部分,不四捨五入。code

class Solution { public int mySqrt(int x) { if(x<=1) return x; int l=1,h=x; while(l<=h){ int mid=l+(h-l)/2; int sqrt=x/mid; if(sqrt==mid){ return mid; } else if(sqrt<mid){ h=mid-1; } else{ l=mid+1; } } return h; } }
相關文章
相關標籤/搜索