# C# LeetCode刷题 - Leetcode 633. 平方数之和 - 题解

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

### C#版 - Leetcode 633. 平方数之和 - 题解

Leetcode 633 - Sum of square number

## 题目描述

输入: 5



输入: 3



Input:
5
2
100

true
true
true

 ●  题目难度: 简单
- 通过次数：1.1K - 提交次数：4.8K - 贡献者： [Stomach_ache](https://leetcode.com/stomach_ache/)

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
double diff = c - i*i;
if ((int)(Math.Ceiling(Math.Sqrt(diff))) == (int)(Math.Floor(Math.Sqrt(diff))))
return true;
}

return false;
}
}


Rank:

You are here! Your runtime beats 56.14% of csharp submissions.

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
int diff = c - i*i;
if (IsPerfectSquare(diff))
return true;
}

return false;
}
private bool IsPerfectSquare(int num)
{
double sq1 = Math.Sqrt(num);
int sq2 = (int)Math.Sqrt(num);
if (Math.Abs(sq1 - (double)sq2) < 10e-10)
return true;
return false;
}
}


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

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; i <= c && c - i * i >= 0; i++)
{
int diff = c - i*i;
if (IsPerfectSquare(diff))
return true;
}

return false;
}
public bool IsPerfectSquare(int num)
{
if ((0x0213 & (1 << (num & 15))) != 0)
{
int t = (int)Math.Floor(Math.Sqrt((double)num) + 0.5);
return t * t == num;
}
return false;
}
}


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

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - i * i >= 0; i++)
{
long diff = c - i*i;
if (IsSquareFast(diff))
return true;
}

return false;
}

bool IsSquareFast(long n)
{
if ((0x2030213 & (1 << (int)(n & 31))) > 0)
{
long t = (long)Math.Round(Math.Sqrt((double)n));
bool result = t * t == n;
return result;
}
return false;
}
}


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

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
double diff = c - i*i;
if (Math.Abs(Math.Sqrt(diff) % 1) < 0.000001)
return true;
}

return false;
}
}


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

Reference:

Fast way to test whether a number is a square
https://www.johndcook.com/blog/2008/11/17/fast-way-to-test-whether-a-number-is-a-square/

06-22 1752
10-11 1178

03-24 62
10-16 150
01-08 1815
06-14 934
04-28 877
08-27 1042
10-20
06-21 641