367. Valid Perfect Square
Test instructions: Do not use the API to determine whether an integer is a square number.
The idea of starting is to determine whether the square number is directly in the dichotomy.
The wrong code:
1 Public BooleanIsperfectsquare (intnum) {2 //binary Search3 intI=0;4 intn=num;5 while(i<=N) {6 intmid=i+ (n-i)/2;7 intsquare=mid*mid;8 if(Square==num)return true;9 Else if(square<num) {TenI=mid+1; One } A Else { -N=mid-1; - } the } - return false; -}
The multiplication of the 7th row overflows and the test times out (it should be that the overflow causes the loop to run continuously).
Modify the following code to pass the test.
1 Public BooleanIsperfectsquare (intnum) {2 //binary Search3 intI=1;4 intN= (num>>1) +1;5 while(i<=N) {6 intmid=i+ (n-i)/2;7 LongSquare= (Long) mid*mid;8 if(square== (Long) num)return true;9 Else if(square< (Long) num) {TenI=mid+1; One } A Else { -N=mid-1; - } the } - return false; -}
Determines whether an integer is a square number