Is My Solution for the LeetCode Perfect Square Problem Good Enough?

0
4
Asked By CuriousCoder97 On

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

Answered By TechExplorer42 On

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?

CuriousCoder97 -

It's just to ensure the multiplication is done in 64-bit, which helps with larger numbers up to INT_MAX.

Answered By CodeWhiz88 On

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.

Answered By DevNinja81 On

Does it work? If it passes all the test cases on LeetCode, then I’d say you’re good!

CuriousCoder97 -

Yes, it does work. Thanks for confirming!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.