标签:
这道题采用二分查找的方法来做,主要是要注意其中数的溢出问题,使用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;
}
leetcode_69题——Sqrt(x)(二分查找,还有个溢出问题的研究)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4548708.html