# Java Exercises: Test if a given number is a perfect square or not

## Java Basic: Exercise-197 with Solution

Write a Java program to test if a given number (positive integer ) is a perfect square or not.

Input number: 3 Output: 1 2 3 8 9 4 7 6 5

Pictorial Presentation: Sample Solution:

Java Code:

``````import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in .nextInt();
System.out.print("Is the said number perfect square? " + is_Perfect_Square(n));
}

public static boolean is_Perfect_Square(int n) {
int x = n % 10;
if (x == 2 || x == 3 || x == 7 || x == 8) {
return false;
}
for (int i = 0; i <= n / 2 + 1; i++) {
if ((long) i * i == n) {
return true;
}
}
return false;
}
}
```
```

Sample Output:

```Input a positive integer:  6
Is the said number perfect square? false
```

Flowchart: Java Code Editor:

Company:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Java: Tips of the Day

How to remove leading zeros from alphanumeric text?

Regex is the best tool for the job; what it should be depends on the problem specification. The following removes leading zeroes, but leaves one if necessary (i.e. it wouldn't just turn "0" to a blank string).

```s.replaceFirst("^0+(?!\$)", "")
```

The ^ anchor will make sure that the 0+ being matched is at the beginning of the input. The (?!\$) negative lookahead ensures that not the entire string will be matched.

Test harness:

```String[] in = {
"01234",         // ""
"0001234a",      // "[1234a]"
"101234",        // ""
"000002829839",  // ""
"0",             // ""
"0000000",       // ""
"0000009",       // ""
"000000z",       // "[z]"
"000000.z",      // "[.z]"
};
for (String s : in) {
System.out.println("[" + s.replaceFirst("^0+(?!\$)", "") + "]");
}```

Ref: https://bit.ly/2Qdcl8a