Solution to Leetcode’s Valid Perfect Square

Valid perfect square description. Leetcode 367

THE NAIVE APPROACH

public static boolean isPerfectSquareWithBruteForce(int num) {
if (num == 1) return true;
for (int i = 1; i < num; i++) {
if (i*i == num) return true;
}
return false;
}
public static boolean isPerfectSquareWithHalfNumber(int num) {
if (num == 1 || num == 0) return true;
for (int i = 1; i < num/2; i++ ) {
if (i*i == num) return true;
}

return false;
}

A FASTER SOLUTION

public static boolean isPerfectSquareWithBinarySearch(int num) {

double start = 1;
double end = num/2;

if (num == 1) return true;

while (start <= end) {
double mid = Math.floor((end - start)/2) + start;

if (mid * mid == num) {
return true;
}else if (mid * mid < num) {
start = mid + 1;
}else {
end = mid - 1;
}
}
return false;
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Importance of Building Projects

Practical Natural Language Processing for Language Learning: Part 2A.

ICYMI: TT Farm’s Recent Releases and More

About Me — Nevin Katz

Porting Linux’s eBPF to Windows 10 and Windows Server

Minikube Dashboard in AWS EC2

ssh tunnel

Fintech Lecture 3: Open APIs

Suibian: Built with Typescript, Socketio, Postgres

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chunks

Chunks

More from Medium

How did I crack developer interview at Thoughtworks !

Saved by a Songwriter? An Interview with Mary Gauthier

Leetcode 140. Word Break II — Solution Explanation

Return to work smoothly after long sabbatical