There are couple of mistakes in your code (arguably), if reviewed by peer. You are trying to print p
, which is not being re-initialized. Lot of unused variables in your code are removed in this answer.
- You just declared an array, but never used in your program. Not sure whether you wanted to store the user inputs in the array and once all the inputs are received, you might want to compute the reverse and display or compute the reverse and store them in your array directly. So, I just removed it
- The check
a <= 1000000000
I believe is to ensure that values entered are within int
range. Java provides you a constant for this in Integer wrapper class, Integer.MAX_VALUE
(which is 2^31 - 1
)
- The code was lacking modularity. Hence, I extracted it to the method
reverse(int num)
which takes care of computation
Importing all classes from the package is not recommended, rather import only those classes that are used in your code.
import java.util.Scanner;
public class GFG {
public static void main(String[] args) throws Exception {
Scanner ss = new Scanner(System.in);
int T = ss.nextInt();
for (int i = 1; i <= T; i++) {
int a = ss.nextInt();
if (a <= Integer.MAX_VALUE) {
a = reverse(a);
System.out.println(a);
} else {
System.out.println("wrong input");
}
}
}
private static int reverse(int num) {
int reverse = 0;
while( num != 0 ) {
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num/10;
}
return reverse;
}
}
On a side note, if you look at GhostCat's answer of converting the number to String and reversing it, the approach fails for negative numbers.
Example: When user input is -51, the output would be 15-
However, it is common practice in industry to store certain long
values as String
. One such example is credit/debit card numbers