Skip to content

Create 367-Valid-Perfect-Square.cpp #144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions cpp/367-Valid-Perfect-Square.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Given a positive integer num, write a function which returns True if num is a perfect square else False.

Follow up: Do not use any built-in library function such as sqrt.

Constraints: 1 <= num <= 2^31 - 1

*/

class Solution {
public:
bool isPerfectSquare(int num) {
long long start = 0, end = num;
while (start <= end) {
long long mid = (start + end) / 2;
if (mid * mid == num)
return true;
else if (mid * mid > num)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
};