Sqrt(x)
Total Accepted: 52136 Total Submissions: 225527My Submissions
Question Solution
Implement int sqrt(int x)
.
Compute and return the square root of x.
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题采用二分查找的方法来做,主要是要注意其中数的溢出问题,使用unsigned int,而4个字节,所以是最大值为2^32-1=4294967295,所以再选取中间的值的值时
不能大于65535(因为65535的平方已经是最大值了,再大了计算不了,为溢出)
#include<iostream> #include<math.h> #include<stdlib.h> using namespace std; int mySqrt(int x){ if(x==0||x==1) return x; unsigned int a=0; unsigned int b=x; unsigned int c; while(1) { if(a==b) return a-1; c=(a+b)/2; if(c>65535) c=65535; if(c*c==x) return c; else if(c*c<x) { a=c+1; } else { b=c; } } } int main() { int x=2147395599; cout<<mySqrt(x)<<endl; }
时间: 2024-10-08 09:21:36