C++ question:
Write a recursive function that takes a non-negative integer as an argument and returns an integer with the same digits of the argument in reverse order (i.e. in order from right to left). All trailing zeros in the argument number are omitted. For example, if the argument is 76038, it would return 83067 and if the argument is 45600 it returns 654.
#include <iostream> #include <cmath> using namespace std; int reverse(int n, int length) { if (length == 1) { return n; } else { int b = n % 10; n = n / 10; return (int) ((b * pow(10, length - 1)) + reverse(n, --length)); } } int length(int n) { if (n == 0) { return 0; } else { return 1 + length(n/10); } } int main() { int n; cout << "Enter a number: "; cin >> n; int reversedNumber = reverse(n, length(n)); cout << reversedNumber << endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.