Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as
sqrt
.
給予正整數 num ,寫一個函式回傳 num 是否為完美平方數。
提示:不要使用任何內建函式庫的函式,例如
sqrt
。
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
sqrt
,那就自己實作一個就好了。
sqrt
的方法。
class Solution {
public:
int mySqrt(int x) {
// x1 = x0 - f(x)/f'(x)
// f(x) = x^2 - a = 0
// x1 = x0 - x^2 - a / 2x
if(x == 0) return 0;
double a = x, a2 = x;
do
{
a = a2;
a2 = a - (a * a - x) / (2 * a);
} while(abs(a - a2) > 0.00001);
return (int)floor(a2);
}
bool isPerfectSquare(int num) {
int temp = mySqrt(num);
return temp * temp == num;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up