blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Determining an Integer Square Root (12934)

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.

[Programmers / JAVA] Level 1 Determining an Integer Square Root (12934)

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.
RWB0104
@RWBwritten at 2021-12-18 11:46:29
Programmers

시리즈 모아보기

Programmers

54 / 78
RankLanguage 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.
nreturn
121144
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 (n+1)2(\sqrt{n} + 1)^2.


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 (n+1)2(\sqrt{n} + 1)^2.

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;
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08