SQRT (x) Implement
int sqrt(int x)
.
Compute and return the square root of X.
Hide TagsBinary Search MathHide Similar Problems(M) Pow (x, N) (m) Valid Perfect SquareTime Limit exceed solution if start from 0.
Public classSolution { Public intMYSQRT (intx) {if(x = = 0) return0; intLowerbound = 1; intHigherbound = 2; //search for a boundary while(true) { intSquare = Lowerbound *lowerbound; if(Square = =x)returnlowerbound; if(Square <x) {lowerbound=Higherbound; Higherbound= Higherbound * 2; } Else{lowerbound= LOWERBOUND/2; Higherbound= HIGHERBOUND/2; Break; } } intleft = lowerbound + 1; intright = HigherBound-1; while(Left <=Right ) { intMid = (left + right)/2; intSquare = Mid *mid; if(Square = =x)returnmid; if(Square <x) left= Mid + 1; Else Right= Mid-1; } returnLeft-1; }}
Another solution if start from both ends of Integer range.
Public classSolution { Public intMYSQRT (intx) {if(x = = 0) return0; intleft = 1, right =Integer.max_value; while(Left <=Right ) { intMid = left + (right-left)/2; inttemp = X/mid;//Use division because mid*mid may > Integer.max if(Mid = =temp)returnmid; if(Mid >temp) Right= Mid-1; Else Left= Mid + 1; } returnLeft-1; }}
367. Valid Perfect Square
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note:do no built-in library function such as sqrt
.
Example 1:
Input:16returns:true
Example 2:
Input:14returns:false
Hide TagsBinary Search MathHide Similar Problems(M) Sqrt (x)
Public classSolution { Public BooleanIsperfectsquare (intnum) { if(num = = 0) return true; intleft = 1, right =Integer.max_value; while(Left <=Right ) { intMid = left + (right-left)/2; inttemp = Num/mid;//Use division because mid*mid may > Integer.max if(Mid = =temp) { if(Mid*mid = =num)return true; return false;//Here is the trap! e.g. num = 5, mid = 2 } if(Mid >temp) Right= Mid-1; Else Left= Mid + 1; } return false; }}
SQRT (x) && 367. Valid Perfect Square