SQRT (x)
Implement int sqrt(int x)
.
Compute and return the square root of
x. Analysis: Scenario One: Traverse 0~n, first occurrence
i * i > N,Return to I-1. Scenario 2:2 Search: (1) when n = 0, or n = 1 o'clock, returns N (2) initialized s = 0, E = n; Note that the value of E must not exceed Int_max's root value, i.e. E is not greater than46341, otherwise the mid * mid value may overflow, resulting in an error in the calculation result. (3) When S < E, Mid = (s + e)/2; When Mid * Mid < N, s = mid; When Mid * mid > N, e = mid; When mid * mid = N, return mid. When s + 1 = e, the description s * S < n < (s + 1) * (S + 1), i.e. S is the evaluated value. Otherwise, the loop continues to execute.
1 classSolution2 {3 Public:4 intsqrtintN)5 {6 intm =N;7 if(n = =0|| n = =1)8 returnN;9 Ten ints =0, E = N, mid =0; One if(E >46341) AE =46341; - - while(S <e) the { -Mid = (s + e)/2; - if(Mid * Mid <N) -s =mid; + Else if(Mid * mid >N) -E =mid; + Else A returnmid; at - if(S +1==e) - returns; - } - } -};
SQRT (x)