leetcode-69-Sqrt(x)
阿新 • • 發佈:2018-04-05
溢出 code 立即數 ood XA 是什麽 ati 執行 overflow
題目描述:
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated
要實現的函數:
int mySqrt(int x)
代碼:
#include<climits>
int mySqrt(int x)
{
if(x>=2147395600&&x<=INT_MAX)//**
return 46340;//**
for(int i=0;i<=x;i++)
{
if((i*i<=x)&&((i+1)*(i+1)>x))
return i;
}
}
說明:
1、本題目采用上述代碼很容易實現,但是有一個問題就是時間花費巨大,采用二分查找會好很多……
2、本題目若是要求輸出sqrt(x)的完整結果,而不僅僅是整數部分,那麽應該采取牛頓叠代法或者泰勒公式展開的方法。最開始就考慮了泰勒展開的方法,後來重新看了下題目,發現打擾了走錯路了……
3、c++對於立即數的存儲和處理采用的是int類型。
cout<<46341*46341<<endl;的時候,會提示“interger overflow”,因為INT_MAX比46341*46341小。
同理,如果if(46341*46341>INT_MAX)cout<<“good“<<endl;代碼運行不會輸出good的,因為這時候已經溢出了,結果不會大於INT_MAX的。
之所以要提這一點,是因為最開始的代碼中,沒有//**標記的那兩行。
各位同學想想若是直接去掉了這兩行,當x=INT_MAX的時候,mySqrt(x)執行結果會是什麽?
leetcode-69-Sqrt(x)