[Programmers / JAVA] Level 1 Determining an Integer Square Root (12934)
[Programmers / JAVA] Level 1 Determining an Integer Square Root (12934)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
🔗 Determining an Integer Square Root
For any positive integer n, we want to determine whether n is the square of some positive integer x.
Complete the function that returns the square of x + 1 if n is the square of a positive integer x, or returns -1 if n is not the square of a positive integer.
- n is a positive integer between 1 and 50000000000000, inclusive.
| n | return |
|---|---|
| 121 | 144 |
| 3 | -1 |
Input/Output Example #1
Since 121 is the square of the positive integer 11, it returns 144, the square of (11+1).
Input/Output Example #2
Since 3 is not the square of a positive integer, it returns -1.
An algorithm that checks whether n is the square of some number, and if so, returns the square of (that number's square root + 1).
If it is a perfect square, return .
To check whether n is a perfect square, check whether Math.sqrt(n) matches its integer part.
If this check confirms that n is the square of some number, return the value of .
If not, return -1.
JAVA
/** * Determining an Integer Square Root class * * @author RWB * @since 2021.12.13 Mon 19:15:59 */ class Solution { /** * Method that returns the answer * * @param n: [long] integer * * @return [long] answer */ public long solution(long n) { double sqrt = Math.sqrt(n); long num = (long) sqrt; return sqrt == num ? (long) Math.pow(sqrt + 1, 2) : -1; } }
