Reverse Number with while loop - Java Language Basics

Java examples for Language Basics:while

Description

Reverse Number with while loop

Demo Code


public class Main {
 
        public static void main(String[] args) {
                int number = 1234;
                int reversedNumber = 0;
                int temp = 0;
               /*from w w w . ja v a 2 s. c om*/
                while(number > 0){
                       
                        //use modulus operator to strip off the last digit
                        temp = number%10;
                       
                        //create the reversed number
                        reversedNumber = reversedNumber * 10 + temp;
                        number = number/10;
                         
                }
               
                System.out.println("Reversed Number is: " + reversedNumber);
        }
}

Result


Related Tutorials