Seeking Guidance on Java Program for Reversing Numbers !!

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Seeking Guidance on Java Program for Reversing Numbers !!

dereektheler
Hello everyone,

I am currently learning Java and came across an exercise where I need to write a program that reverses a given number. For example.., if the input is 1234, the output should be 4321. I attempted to implement this using a while loop to extract each digit and construct the reversed number,,, but I am encountering some issues with my code.

Here's what I have so far :-


public class ReverseNumber {
    public static void main(String[] args) {
        int number = 1234; // Example input
        int reversed = 0;
       
        while (number != 0) {
            int digit = number % 10;
            reversed = reversed * 10 + digit;
            number /= 10;
        }
       
        System.out.println("Reversed Number: " + reversed);
    }
}

When I run this code.., it doesn't produce the expected output. Could someone please help me identify what's going wrong: ?? Any guidance or suggestions to improve this code would be greatly appreciated.

Thank you in advance for your assistance !!

With Regards,
Derek Theler

workday