From 5f88b6447a3461a53207affb6713ffa7e15c7079 Mon Sep 17 00:00:00 2001 From: Samruddhi Ghodake <72791227+samughodake@users.noreply.github.com> Date: Tue, 28 Sep 2021 18:25:54 +0530 Subject: [PATCH] chore(CPlusPlus): add reverse digits (#492) --- algorithms/CPlusPlus/Maths/reverse-digits.cpp | 47 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 algorithms/CPlusPlus/Maths/reverse-digits.cpp diff --git a/algorithms/CPlusPlus/Maths/reverse-digits.cpp b/algorithms/CPlusPlus/Maths/reverse-digits.cpp new file mode 100644 index 00000000..78417156 --- /dev/null +++ b/algorithms/CPlusPlus/Maths/reverse-digits.cpp @@ -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 +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 +*/ \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 1b7052cf..0cf38bcf 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -123,6 +123,7 @@ 3. [Prime Sieve](Maths/prime-sieve.cpp) 4. [Fibonacci Series](Maths/fibonaccci-series.cpp) 5. [Armstrong Number](Maths/armstrong.cpp) +6. [Reverse digit of a number](Maths/reverse-digits.cpp) # Recursion