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

LintCode 697. 判断是否为平方数之和

时间:2018-02-01 17:17:45      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:一个   穷举   nbsp   blog   --   col   style   pre   需要   

---恢复内容开始---

给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c.

样例

给出 n = 5
返回 true // 1 * 1 + 2 * 2 = 5
给出 n = -5
返回 false

 

解:一般穷举解会超时

可用n=sqrt(num),sqrt是开根号,n等于根号num,设a*a+b*b=n*n=num,(得a与b都小于等于n) ,即b=sqrt(num-a*a)<=n

class Solution {
public:
    /*
     * @param : the given number
     * @return: whether whether there‘re two integers
     */
    bool checkSumOfSquareNumbers(int num) {
        // write your code here
        if(num<0) return false;
        if(num==0) return true;
       
        int n=sqrt(num);
        for(int a=0;a<=n;a++)
        {
           int b=0;
           if((b=sqrt(num-a*a))<=n) 
           {
               if((b*b+a*a)==num)
                return true;
           }
          
        }
        
        return false;
    }
   
};

 

 

LintCode 697. 判断是否为平方数之和

标签:一个   穷举   nbsp   blog   --   col   style   pre   需要   

原文地址:https://www.cnblogs.com/zslhg903/p/8399137.html

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