码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode: Check Sum of Square Numbers

时间:2017-10-05 20:55:48      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:active   else   body   tab   script   public   lintcode   panel   遇到   

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

标签:active   else   body   tab   script   public   lintcode   panel   遇到   

原文地址:http://www.cnblogs.com/gousheng/p/7629933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!