I'm working on LeetCode Problem 367, which is about determining if a given positive integer is a perfect square. The problem states that a perfect square is an integer that can be expressed as the square of another integer, like 1, 4, 9, 16, etc. Here's my implementation in C++:
```cpp
bool isPerfectSquare(int num) {
int b = (int)sqrt(num);
return 1LL * b * b == num;
}
```
Is this code acceptable? I've noted that it should have a time complexity of O(1) and a space complexity of O(1).
3 Answers
The concept seems solid, but I’m a bit confused about the use of `1LL`. What’s that about? Also, have you thought of how to do this without the built-in `sqrt()` function?
Your implementation works, but take some time to really understand how `sqrt()` behaves in computing. This is often a topic discussed in CS courses, and there are various algorithms and optimizations out there.
Does it work? If it passes all the test cases on LeetCode, then I’d say you’re good!
Yes, it does work. Thanks for confirming!
It's just to ensure the multiplication is done in 64-bit, which helps with larger numbers up to INT_MAX.