Implement int
sqrt(int x)
.
Compute and return the square root of x.
TestCases:
input | output | expected | |
---|---|---|---|
0 | 0 | 0 | |
1 | 1 | 1 | |
2 | 1 | 1 | |
3 | 1 | 1 | |
4 | 2 | 2 | |
5 | 2 | 2 | |
6 | 2 | 2 | |
7 | 2 | 2 | |
8 | 2 | 2 | |
9 | 3 | 3 | |
10 | 3 | 3 | |
1024 | 32 | 32 | |
8192 | 90 | 90 | |
2147395599 | 46339 | 46339 | |
2147395600 | 46340 | 46340 | |
2147483647 | 46340 | 46340 |
要注意的问题:
1. sqrt(10)=3
2. int由32bit表示,不可以越界!一般思路:sqrt(x) < x/2, 从0-x/2开始做binary search. 但x>2^16时 (x/2)^2会int溢出。必须设定搜索上限
class Solution { public: int sqrt(int num) { // Start typing your C/C++ solution below // DO NOT write int main() function int start=0; int end=0; int tmp=num; int digits=0; //get the upperbound of its sqrt while(tmp > 0) { digits++; tmp=tmp/10; } for(int i=0;i<(digits+1)/2;i++) end=end*10+9; if(end > 46340) end=46340; //the largest for 32-bit integer in C++ if(end > num/2+1 ) end=(num+1)/2; int med=0; while(start <= end) { med=(start+end+1)/2; if( med >= 46340) return 46340; if(med*med <= num && (med+1)*(med+1)>num) return med; if(med*med < num) start=med; else end=med; } } };
思路2: 牛顿搜索: http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number
class Solution { public: int sqrt(int x) { float n_search_seed=10; float num=(float)x; float prev_seed=0; float EPS = 0.00000001; do //empiracle 20 loops should be good enough { prev_seed = n_search_seed; n_search_seed=n_search_seed - (n_search_seed*n_search_seed - num)/(2*n_search_seed); }while(abs(prev_seed - n_search_seed) > EPS); int result=n_search_seed; if(result*result > x) result--; return result; } };