Valid Perfect Square - Math - Easy - LeetCode
💻 coding

Valid Perfect Square - Math - Easy - LeetCode

1 min read 98 words
1 min read
ShareWhatsAppPost on X
  • 1The function checks if a positive integer is a perfect square without using built-in functions like sqrt.
  • 2It uses a while loop to incrementally sum odd integers until the sum equals or exceeds the input number.
  • 3The solution has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The function checks if a positive integer is a perfect square without using built-in functions like sqrt."

Valid Perfect Square - Math - Easy - LeetCode

Given a positive integer num, write a function that returns True if num is a perfect square else False.

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

Example 1:

Input: num = 16 Output: true Example 2:

Input: num = 14 Output: false

Constraints:

1 <= num <= 2^31 - 1

public class Solution {
 public bool IsPerfectSquare(int num) {
 int i = 1;
 int sum = 0;
 while (sum < num) {
 sum += i;
 if(sum<0){
 return false;
 }
 i += 2;
 }
 return sum==num;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 1 min read · 98 words

Part of AskGif Blog · coding

You might also like

Valid Perfect Square - Math - Easy - LeetCode | AskGif Blog