Write a function that takes an integer value and returns the number with its digits reversed. For example, given the number 12345, the function should return 54321.
Solution :
#include <iostream> #include <iomanip> using std::setw; using std::setfill; using namespace std; int reverseDigits( int ); int width( int ); int main() { int number; cout << "Enter a number between 1 and 9999: "; cin >> number; cout << "The number with its digits reversed is: " << setw( ( width( number ) ) ) << setfill( '0' ) << reverseDigits( number ) << endl;return 0; } int reverseDigits( int n ) { int reverse = 0, divisor = 1000, multiplier = 1; while ( n > 10 ) { if ( n >= divisor ) { reverse += n / divisor * multiplier; n %= divisor; divisor /= 10; multiplier *= 10; } else divisor /= 10; } reverse += n * multiplier; return reverse; } int width( int n ) { if ( n /= 1000 ) return 4; else if ( n /= 100 ) return 3; else if ( n /= 10 ) return 2; else return 1; }
Output:Enter a number between 1 and 9999:8765 The number with its digits reversed is: 5678
Post A Comment:
0 comments: