lintcode: Check Sum of Square Numbers

Posted 狗剩的美丽家园

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode: Check Sum of Square Numbers相关的知识,希望对你有一定的参考价值。

Check Sum of Square Numbers 

Given a integer c, your task is to decide whether there‘re two integers a and b such that a^2 + b^2 = c.

样例

Given n = 5
Return true // 1 * 1 + 2 * 2 = 5

Given n = -5
Return false

代码

 1 class Solution {
 2 public:
 3     /*
 4      * @param : the given number
 5      * @return: whether whether there‘re two integers
 6      */
 7     bool checkSumOfSquareNumbers(int num) {
 8         // write your code here
 9         if (num < 0) {
10             return false;
11         }
12         int c = floor(sqrt(num));
13         int i = c;
14         if (i * i == num) return true;
15         int j = 1;
16         while (j <= i) {
17             if (i * i + j * j == num) {
18                 return true;
19             } else if (i * i + j * j < num) {
20                 j++;
21             } else {
22                 i--;
23             }
24         }
25         return false;
26     }
27 };

 

以上是关于lintcode: Check Sum of Square Numbers的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]142. O Check Power of 2

[LintCode] O Check Power of 2

[GeeksForGeeks] Check sum of covered and uncovered nodes of binary tree

lintcode-medium-4 Sum

check whether the subset(no need to be consective) and be sum of X

Lintcode: Interval Sum