# C# LeetCode刷题 - Leetcode367. 有效的完全平方数 - 题解

http://blog.csdn.net/lzuacm。

### C#版 - Leetcode367. 有效的完全平方数 - 题解

Leetcode 367 - Valid Perfect Square

### 题目描述

**归功于:**

 ●  题目难度: 简单

1.利用数学公式 $k^2 = 1 + 3 + \cdots +(2\cdot k - 1)$ .

2.自己实现sqrt函数的功能，最快的方法当属 Babylonian method.

3.二分查找

public class Solution
{
public bool IsPerfectSquare(int num)
{
int i = 1;
while (num > 0)
{
num -= i;
i += 2;
}

if (num == 0)
return true;
return false;
}
}


Rank:
You are here! Your runtime beats 94.68 % of csharp submissions.

public class Solution
{
public const double eps = 1e-10;
public bool IsPerfectSquare(int num)
{
double sq1 = SquareRoot(num);
int sq2 = (int)SquareRoot(num);
if (sq1 - (double)sq2 < eps && sq1 - (double)sq2 > -eps)
return true;
return false;
}
public double SquareRoot(double x)
{
if (x == 0)
return 0;

double r = x / 2;
double last = 0;
int maxIters = 100;

for (int i = 0; i < maxIters; i++)
{
r = (r + x / r) / 2;
if (r - last < eps && r - last > -eps)
break;

last = r;
}

return r;
}
}


Rank:
You are here! Your runtime beats 94.68 % of csharp submissions

11-13 79
08-04 3478

10-10 92
06-23 152