Be the first user to complete this post
|
Add to List |
232. Check whether the given number is a perfect square
Objective: Given an integer check whether it is a perfect square.
Example:
number = 37 Output: false number = 49 Output: true
This is a fun puzzle that is asked in the interview.
Approach:
- Say the number is n.
- Start a loop from 1 to n/2.
- During iteration, for every integer ‘i’, calculate x = i*i.
- Now with this ‘x’ there are 3 possibilities.
- If x == n then n is a perfect square, return true
- If x > n then x has crossed the n, and n is not perfect square. Return false
- If the above steps a or b are not true then continue.
Time Complexity: O(sqrt(n))
Output:
37 is square: false 49 is square: true