此題是要實現如何做一個開根號的方法。有個陷阱是 int 遇到太大的數字會溢位。
LeetCode 題目連結
https://leetcode.com/problems/sqrtx/
題目
Implement
int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4 Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
Java 程式碼
class Solution { public int mySqrt(int x) { long lastIndex = 0; for(long i = 1;i*i<=(long)x;i++){ long sum = i *i; if(sum <= x){ lastIndex = i; } } return (int)lastIndex; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言