Mid From PDF Coding C# Coding Interview

Check if a number is a perfect square?

public bool IsPerfectSquare(int num) {
if (num < 0) return false;
int left = 0, right = num;

while (left <= right) {

int mid = left + (right - left) / 2;
long sq = (long)mid * mid;
if (sq == num) return true;
else if (sq < num) left = mid + 1;
else right = mid - 1;
}
return false;
}

Explanation:

Binary search for integer square root and check if square equals num.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details