Problem
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
Solution: Math
Time complexity: O(sqrt(c))
Space complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua // Running time: 4 ms class Solution { public: bool judgeSquareSum(int c) { int m = sqrt(c); for (int a = 0; a <= m; ++a) { int b = round(sqrt(c - a * a)); if (a * a + b * b == c) return true; } return false; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment