您的位置:首页 > 其它

[Leetcode] 633. Sum of Square Numbers 解题报告

2018-01-20 11:22 330 查看
题目

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: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5


Example 2:

Input: 3
Output: False

思路

一个一个试了。这种题目最好是消除不必要的循环,并且少用开方和除法运算,这样可以大大提高效率。

代码

class Solution {
public:
    bool judgeSquareSum(int c) {
        int half_c = (c >> 1), sb, b;
        for (int a = 0; a * a <= half_c; ++a) {
            sb = c - a * a;
            b = sqrt(sb);
            if (b * b == sb) {
                return true;
            }
        }
        return false;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: