chore(CPlusPlus): add reverse digits (#492)
parent
06ab1015e8
commit
5f88b6447a
|
@ -0,0 +1,47 @@
|
||||||
|
/*
|
||||||
|
Description: A program to reverse the digits of a number.
|
||||||
|
|
||||||
|
Approach: Running a while loop over number till it becomes 0
|
||||||
|
Multiplying the result variable to 10 each time.
|
||||||
|
Taking the modulus of number at every iteration and adding it to the final result to generate the reverse.
|
||||||
|
Dividing the number by 10 at every iteration.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
//function
|
||||||
|
long reverse_digit(long n)
|
||||||
|
{
|
||||||
|
//result variable
|
||||||
|
long num = 0;
|
||||||
|
while (n != 0)
|
||||||
|
{
|
||||||
|
//storing the last digit of n in temp variable
|
||||||
|
long temp = n % 10;
|
||||||
|
//multiplying the num variable into 10 and adding temp value to it
|
||||||
|
num = num * 10 + temp;
|
||||||
|
//Dividing n by 10 at each iteration
|
||||||
|
n = n / 10;
|
||||||
|
}
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
//main starts
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
cout << "Enter a number\n";
|
||||||
|
long n;
|
||||||
|
cin >> n;
|
||||||
|
cout << "Reverse number is: ";
|
||||||
|
cout << reverse_digit(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Input:
|
||||||
|
Enter a number
|
||||||
|
1234
|
||||||
|
|
||||||
|
Output:
|
||||||
|
Reverse number is: 4321
|
||||||
|
*/
|
|
@ -123,6 +123,7 @@
|
||||||
3. [Prime Sieve](Maths/prime-sieve.cpp)
|
3. [Prime Sieve](Maths/prime-sieve.cpp)
|
||||||
4. [Fibonacci Series](Maths/fibonaccci-series.cpp)
|
4. [Fibonacci Series](Maths/fibonaccci-series.cpp)
|
||||||
5. [Armstrong Number](Maths/armstrong.cpp)
|
5. [Armstrong Number](Maths/armstrong.cpp)
|
||||||
|
6. [Reverse digit of a number](Maths/reverse-digits.cpp)
|
||||||
|
|
||||||
# Recursion
|
# Recursion
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue