美文网首页
LintCode 697. Check Sum of Squar

LintCode 697. Check Sum of Squar

作者: Andiedie | 来源:发表于2017-10-12 23:49 被阅读0次

    原题

    LintCode 697. Check Sum of Square Numbers

    Description

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

    Example

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

    Given n = -5
    Return false

    代码

    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;
            int right = floor(sqrt(num));
            if (right * right == num) return true;
            int left = 1;
            while (left < right) {
                int result = left * left + right * right;
                if (result == num) {
                    return true;
                } else if (result > num) {
                    right--;
                } else {
                    left++;
                }
            }
            return false;
        }
    };
    

    相关文章

      网友评论

          本文标题:LintCode 697. Check Sum of Squar

          本文链接:https://www.haomeiwen.com/subject/hxsayxtx.html