Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

Java program to reverse a number

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
I wrote this Java program to reverse a number using a while loop. Is this the correct approach, or is there a more efficient way to do this in Java?

class ReverseNumber {
   public static void main(String[] args) {
       int num = 1234;
       int reversed = 0;

       while (num != 0) {
           int digit = num % 10;
           reversed = reversed * 10 + digit;
           num /= 10;
       }

       System.out.println("Reversed Number = " + reversed);
   }
}
 
Sheriff
Posts: 9090
670
Mac OS X Spring VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Duplicate of https://coderanch.com/t/1010640/java/Java-program-reverse-number

Locking this thread.
    Bookmark Topic Watch Topic
  • New Topic