
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Write a program to reverse digits of a number in C++
A program to reverse digits of a number will interchange the position of the digits and reverse there order.
Let’s suppose be a number abcde the reverse will be edcba.
Let’s take an example to understand the problem,
Input
n = 786521
Output
125687
To reverse digits of the number, we will take each digit of the number from MSB(unit digit) and add it to reverse number variable, after this divide the original number by 10 and the reverse_number is multiplied by 10. This will be done until the number becomes 0.
This repetitive process can be accomplished by two methods, iteration, and recursion, we will create a program to create illustrate both the method.
Example
Method 1: Iterative approach
#include <iostream> using namespace std; int reversDigitsIt(int n) { int reverseNumber = 0; while(n > 0){ reverseNumber = reverseNumber*10 + n%10; n /= 10; } return reverseNumber; } int main() { int n = 4562; cout<<"The number is : "<<n<<endl; cout<<"Reverse of number is "<<reversDigitsIt(n); return 0; }
Output
The number is : 4562 Reverse of number is 2654
Example
Method 2: Recursive Approach
#include <iostream> using namespace std; int reverseNumber = 0; int numPos = 1; void reversDigitsRec(int n) { if(n > 0){ reversDigitsRec(n/10); reverseNumber += (n%10)*numPos; numPos *= 10; } } int main() { int n = 4562; cout<<"The number is : "<<n<<endl; reversDigitsRec(n); cout<<"Reverse of number is "<<reverseNumber; return 0; }
Output
The number is : 4562 Reverse of number is 2654
- Related Articles
- Write an Efficient C Program to Reverse Bits of a Number in C++
- Write a Golang program to reverse a number
- Write a C program to reverse array
- C++ Program to Reverse a Number
- Write a program in Python to count the number of digits in a given number N
- Write a program to reverse an array or string in C++
- Write a Golang program to find the sum of digits for a given number
- C++ Program to Sum the digits of a given number
- Write a Golang program to reverse a string
- Write program to reverse a String without using reverse() method in Java?
- Java Program to Reverse a Number
- Swift Program to Reverse a Number
- Haskell Program to Reverse a Number
- Kotlin Program to Reverse a Number
- Write a C program to Reverse a string without using a library function

Advertisements