Leetcode 633.平方数之和【C++】

本文最后更新于:2022年3月23日 晚上

地址:https://leetcode-cn.com/problems/sum-of-square-numbers/

题目

给定一个非负整数 c ,你要判断是否存在两个整数 ab,使得 a2 + b2 = c

示例1:

输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5

示例2:

输入: 3
输出: False

解题思路

双指针。设置返回值 ret 默认为 false,分别取最小的数(0)和最大的数,最大的数可以直接使用 sqrt() 函数求目标数的平方根并向下取整,小数的平方与大数的平方求和,若大于目标值,大数减1,继续循环;若小于目标值,小数加1,继续循环;直到与目标值相等(置 rettrue)或者小数不再小于大数,跳出循环。返回结果。

代码

class Solution {
public:
    bool judgeSquareSum(int c) {
        bool ret = false;
        long small = 0;
        long big = int(sqrt(c));
        while (small <= big)
        {
            if (big * big > c || small * small + big * big > c)
            {
                big--;
                continue;
            }
            else if (small * small + big * big < c)
            {
                small++;
                continue;
            }
            else
            {
                ret = true;
                break;
            }
        }
        return ret;
    }
};

Leetcode 633.平方数之和【C++】
https://mxy493.xyz/202003064703/
作者
mxy
发布于
2020年3月6日
许可协议