REVERSE OF A NUMBER
Constraint :
Input must be an integer
Before going to reverse our number first, focus on the mathematics behind it.
Any number like 12548 is also can written as 10000 X 1 + 1000 X 2 + 100 X 5 + 10 X 4 + 8, after reverse number will become 84521 which can also be written as 10000 X 8 + 1000 X 4 + 100 X 5 + 10 X 2 + 1, if you will focus on the pattern then, you would realize that, instead of reverse number we just need to change the multiply part because addition support commutative property (a+b = b+a).
Focusing points
Every time number of tens multiple increases for last digits.
Every time number of tens multiple decrease for starting digits
Number of zero's with first digit are equal to length of a number
Number of zero's with last digit are NOT available.
Conclusion
If we want to reverse our number then, first we have to decrease zero's with starting digit, and add zero's to the last digit.
Logic Building
Step 1: Decreasing number of zero's means we have to divide by the 10's multiple
Step 2: Increasing number of zero's means, we have to multiply by the 10's multiple.
Step 3: For all this first, we require digits. For getting digits from a number we require '%' operator which will help us to get our digits from number. for e.g. 125 % 10 = 5 by this approach we will get our digits.
Step 4: Code
public class Main {
public static void main(String[] args) {
int number = 12345;
int newNumber = 0;
while(number > 0){
int digit = number % 10;
newNumber = newNumber * 10 +digit;
number = number / 10;
}
System.out.println(newNumber);
}
}
Try this code.
Comments