Leetcode 633. Sum of Square Numbers
Given a non-negative integer c
, determine whether there are two integers a
and b
such that:
[ a^2 + b^2 = c ]
Return true
if such a pair exists, and false
otherwise.
c
be zero?
c
can be zero.c
?
c
ranges from (0) to (2^{31} - 1) as it is a non-negative integer type.a
and b
?
a
to 0
and b
to the integer part of the square root of c
.a
is less than or equal to b
, calculate a^2 + b^2
.c
, return true
.c
, increment a
.c
, decrement b
.#include <iostream>
#include <cmath>
class Solution {
public:
bool judgeSquareSum(int c) {
long long a = 0;
long long b = static_cast<long long>(std::sqrt(c));
while (a <= b) {
long long sum = a * a + b * b;
if (sum == c) {
return true;
} else if (sum < c) {
++a;
} else {
--b;
}
}
return false;
}
};
// Example usage:
int main() {
Solution sol;
int testValue = 5;
if (sol.judgeSquareSum(testValue)) {
std::cout << "True" << std::endl;
} else {
std::cout << "False" << std::endl;
}
return 0;
}
c
takes (O(\log c)).0
to (\sqrt{c}). Therefore, the loop runs for (O(\sqrt{c})) iterations.Thus, the overall time complexity is:
[O(\sqrt{c})]
This efficient approach allows determining if there are two integers whose squares sum up to c
without resorting to more computationally expensive methods.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?