Invert a number using Java

Java is a beautiful language if you know how to build your logic. This is the most important thing of all. Invert a number using Java can be done by simply leveraging a very simple mathematical method.

Let’s suppose we want to invert a number 123456.

Steps to invert this number will be as following.

//We will run this in a loop until it ends
invert= invert*10 + number%10 //here it will keep giving us last digit. 
number = number/10 => 123456/10
Example code: Invert a number using Java
// Inverts a number
public long doInvert(long number) {
    long invert = 0;
    while (number != 0) {
        invert = (invert * 10) + (number % 10);
        number = number / 10;
    }
    return invert;
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.