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 };

 

posted on 2017-10-05 20:37  狗剩的美丽家园  阅读(280)  评论(0编辑  收藏  举报

导航