chore(CPlusPlus): add reverse number algorithm (#789)

Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com>
pull/799/head
Ashad 2022-08-11 23:52:36 +05:00 committed by GitHub
parent cef837425c
commit e42f4bb0b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 41 additions and 5 deletions

View File

@ -1,4 +1,4 @@
#include"fib.h"
#include"./fib.h" // NOLINT(build/include)
#include<math.h> // sqrt, pow are used in binet_fib
int recur_fib(int n){

View File

@ -1,5 +1,6 @@
#ifndef FIB_H_INCLUDED
#define FIB_H_INCLUDED
#ifndef ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_
#define ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_
/**
* fib(n) takes nonnegative number n
@ -19,4 +20,4 @@ int iter_log_fib(int n);
int log_fib(int n);
int binet_fib(int n);
#endif
#endif // ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_"

View File

@ -1,5 +1,5 @@
#include<stdio.h>
#include"fib.h"
#include"./fib.h" // NOLINT(build/include)
int main(){
memomizing_fib(); // this is to initialize the memomized table

View File

@ -186,6 +186,7 @@
- [Product of two numbers](Recursion\product-of-numbers.cpp)
- [Product of digits in a number](Recursion\product-of-digits.cpp)
- [Linear search using recursion](Recursion/linear-search.cpp)
- [Reverse a number using recursion](Recursion/reverse-a-number.cpp)
## Number System

View File

@ -0,0 +1,34 @@
/*
Description: Program to reverse integer using recursion
Time complexity: O(n) where n is the number of digits in the integer
*/
#include <cmath>
#include <iostream>
using namespace std;
int Helper(int n ,int base , int ans)
{
if(n < 1)
return ans;
ans = ans * base + (n % 10); // Update the ans for every digit
return Helper(n / 10, base , ans);
}
int Rev(int n)
{
return Helper(n , 10, 0);
}
int main(int argc, char const *argv[])
{
cout << Rev(13579);
return 0;
}
/*
Input: 13579
Output: 97531
*/