REVERSE A NUMBER
Reverse a Number: A Simple Mathematical Trick
Reversing a number is one of the simplest yet most interesting mathematical operations. The process involves rearranging the digits of a number in reverse order to produce a new number. For example:
- Input: 12345
- Output: 54321
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n=sc.nextInt();
int res=0;
int rem;
while(n!=0)
{
rem=n%10;
res=res*10+rem;
n/=10;
}
System.out.print(res);
}
}
How Does it Work?
The reversal process extracts each digit from the number, starting from the last, and reconstructs the number in reverse order. Here's the step-by-step logic:
- Start with the last digit using the modulo operator (
%). - Add this digit to the result after shifting it by multiplying the result by 10.
- Repeat the process by removing the last digit using integer division (
/).
Applications of Reversing Numbers
- Palindrome number checks.
- Cryptography and encoding algorithms.
- Fun programming challenges.
No comments:
Post a Comment