Implement int sqrt(int x)
.
This problem is essentially the largest integer under sqrt (x). Binary search is a more easily thought-out approach. Another, on the internet and learn the other people's Newton iterative method.
This is my original writing, the write is wrong, the complexity is too high
classSolution { Public: intsqrtintx) {if(x <=0) return 0; if(x = =0|| x = =1) returnx; Long LongStart =1; Long Longend = x >>1; intindex =start; while(Start <=end) {Index= (start + end) >>1; if(Index*index = =x)returnindex; Else{ if(End*end <=x)returnend; if(End-start = =1) returnstart; if(Index*index >x) End= Index-1; if(Index*index <x) Start=index; } } returnindex; }};
In fact, the idea of binary search is right, but in some small details in Shanghai need to pay particular attention.
The standard code can be written like this:
classSolution { Public: intsqrtintx) {Long Longi =0; Long Longj = x/2+1; while(I <=j) {Long LongMid = (i + j)/2; Long LongSq = Mid *mid; if(Sq = =x)returnmid; Else if(Sq <x) I= Mid +1; ElseJ= Mid-1; } returnJ; }};
The problem of overflow is considered perfectly. This is the place where I should study hard.
Newton's iterative FA-solving
With this method, you can get an iterative formula Xi+1=xi-(XI2-N)/(2XI) = XI-XI/2 + N/(2xi) = XI/2 + N/2xi = (xi + n/xi)/2.
Then there is the following code:
int sqrt (int x) { if (x = = 0 ) return 0 ; double last = 0 ; double res = 1 ; while (res!= = res; Res = (res + x/res)/2 ; return int
Solve the problem of double, can refer to the above code
DoublesqrtDoublex) {if(x = =0)return 0; DoubleLast =0.0; Doubleres =1.0; while(!Euqal (Res,last)) { Last=Res; Res= (res + x/res)/2; } returnRes;}BOOLEuqal (DoubleNUM1,Doublenum2) { if((NUM1-NUM2) <0.0000001&& (num1-num2) >-0.0000001) return true; Else return false;}
Reference:
Http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html
HAPPYLEETCODE64:SQRT (x)