# C#刷遍Leetcode面试题系列连载（4）：No.633 - 平方数之和

## 系列教程索引

Leetcode 633 - 平方数之和

https://leetcode.com/problems/sum-of-square-numbers/

### 题目描述

输入: 5



输入: 3



Input:

5
2
100


true
true
true


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:

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:

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)  //TRUE only if n mod 16 is 0, 1, 4, or 9
{
int t = (int)Math.Floor(Math.Sqrt((double)num) + 0.5);
return t * t == num;
}
return false;
}
}


Rank:

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:

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:

### 双"指针" 解法:

    public class Solution
{
public bool JudgeSquareSum(int c)
{
var r = (int)Math.Sqrt(c);
var l = 0;
while (l <= r)
{
var sum = l * l + r * r;
if (sum == c)
return true;

if (sum < c)
l++;
else
r--;
}

return false;
}

// 以下为测试
public static void Main(string[] args)
{
var sol = new Solution();
var res = sol.JudgeSquareSum(25);
Console.WriteLine(res);
}
}


Rank:

https://github.com/yanglr/Leetcode-CSharp/tree/master/leetcode633

[1] 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/

[2] Shortest way to check perfect Square? - C#
https://stackoverflow.com/questions/4885925/shortest-way-to-check-perfect-square/4886006#4886006

### 文末彩蛋

posted @ 2019-10-21 08:08  大白技术控  阅读(...)  评论(...编辑  收藏