How to Find the Squares in Java

The challenge

Complete the function that takes an odd integer (0 < n < 1000000) which is the difference between two consecutive perfect squares, and return these squares as a string in the format "bigger-smaller".

Examples

9 --> "25-16" 5 --> "9-4" 7 --> "16-9"
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

public class Solution { public static String findSquares(final int n) { final long a = (n + 1) / 2; final long b = a - 1; return String.format("%d-%d", a * a, b * b); } }
Code language: Java (java)

Option 2:

interface Solution { static String findSquares(long n) { return (n /= 2) * n + 2 * n + 1 + "-" + n * n; } }
Code language: Java (java)

Option 3:

public class Solution{ public static String findSquares(int n){ long n1 = n/2; long n2 = n1+1; return String.valueOf(n2*n2)+"-"+ String.valueOf(n1*n1); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testBasicNumbers() { assertEquals("25-16",Solution.findSquares(9)); } @Test public void testSmallerNumbers() { assertEquals("1-0",Solution.findSquares(1)); } @Test public void testBiggerNumbers() { assertEquals("891136-889249",Solution.findSquares(1887)); assertEquals("2499600016-2499500025",Solution.findSquares(99991)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments