Vishal Vishal - 2 months ago 6
Java Question

Reversing a user input digit using methods

I want to take any user input integer between 1 and 9999 and return that number with its digits reversed. The problem with my code is it's returning the sum of the entered integer and I have no idea how to fix it. This is the code that that I came up with so far:

import java.util.Scanner;
class Reverse{
public static void main(String []args){
Scanner input = new Scanner(;
System.out.print("Enter a number between 1 and 9999: ");
int user = input.nextInt();

if(user>1 && user<9999){
System.out.println("The number with its digits reversed is : " + reverseDigit(user));

System.out.println("Invalid Input");


public static int reverseDigit(int num){

return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); //This is the problem



You could replace :

return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000);


return ((num%10)*1000 + ((num%100)/10 )*100+ ((num%1000)/100)*10 + num/1000);

The reason that the first was wrong is because you get:

last digit:num%10
third digit:num%100)/10
second digit:(num%1000)/100
first digit:num/1000

so you was just adding all the digits before

But the Above works only for numbers from 1000-9999 .So you could replace the reverseDigit method with this simple method that works for every number:

 public static int reverseDigit(int num){
        int reverse=0;
        while( num != 0 )
            reverse = reverse * 10;
            reverse = reverse + num%10;
            num = num/10;
        return reverse;