Algorithm
Input: Take an integer as input from the user.
Initialization: Initialize variables to store the original number (originalNumber
) and the reversed number (reversedNumber
). Set reversedNumber
to 0 initially.
Loop: Use a loop to reverse the digits of the number. Inside the loop:
Extract the last digit of the original number using the modulo operator (originalNumber % 10
).
Multiply the reversed number by 10 and add the extracted digit to it (reversedNumber = reversedNumber * 10 + digit
).
Remove the last digit from the original number (originalNumber = originalNumber / 10
).
Repeat the above steps until the original number becomes 0.
Output: Display the reversed number.
Code Examples
#1 Code Example- C++ Programing to find the Reverse of a Number :- Modulo Operator : '%'
Code -
C++ Programming
#include <iostream>
using namespace std;
//main program
int main ()
{
//variables initialization
int num, reverse = 0, rem;
num=1234;
cout <<"\nThe number is"<<num;
//loop to find reverse number
while(num != 0)
{
rem = num % 10;
reverse = reverse * 10 + rem;
num /= 10;
};
//output
cout <<"\nReversed Number: "<<reverse;
return 0;
}
// Time complexity : O(N)
// Space complexity : O(1)
// where N is number of digits in num
Copy The Code &
Try With Live Editor
Output
Reversed Number: 4321
#2 Code Example- C++ Programing to Reverse a Number. use loop and arithmetic operators:- Division Operator : '/'
Code -
C++ Programming
#include <iostream>
using namespace std;
//main program
int main ()
{
//variables initialization
int num, reverse = 0, rem;
num=1234;
cout <<"\nThe number is"<<num;
//loop to find reverse number
while(num != 0)
{
rem = num % 10;
reverse = reverse * 10 + rem;
num /= 10;
};
//output
cout <<"\nReversed Number: "<<reverse;
return 0;
}
// Time complexity : O(N)
// Space complexity : O(1)
// where N is number of digits in num
Copy The Code &
Try With Live Editor
Output
Reversed Number: 4321
Demonstration
C++ Programing Example to find the Reverse of a Number-DevsEnv