LeetCode 633 Sum of Square Numbers

来源:互联网 发布:封面制作软件ios 编辑:程序博客网 时间:2024/06/08 17:04

题目:

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5Output: TrueExplanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3Output: False
题目链接

题意:

给一个非负的整数c,判断是否存在两个整数a,b满足a2 + b2 = c。

c是非负的,所以a和b的取值可以为0,所以a和b取值应该是[0, sqrt(c)],从0到sqrt(c)枚举一遍,假如c-a*a开平方后可以整除1,那么说明此时的a,b满足条件。

代码如下:

class Solution {public:    bool judgeSquareSum(int c) {        int temp = sqrt(c);        for (int i = 0; i <= temp; i ++) {            int j = c - i * i;            if (fmod(sqrt(j), 1.00) != 0) {                continue;            }            return true;        }        return false;    }};