Functions

closed account (ozyMoG1T)


I tried to make a revered number on c++

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

// return the reverse of a number
int reverse( int number, int reverse_so_far = 0 )
{
    if( number < 0 ) return -reverse( -number ) ;

    if( number < 10 ) return reverse_so_far*10 + number ;

    return reverse( number/10, reverse_so_far*10 + number%10 ) ;
}

int main()
{
    // take the integer input from the user
    std::cout << "number? " ;
    int number ;
    std::cin >> number ;

    // Reverse the input
    const int reverse_number = reverse(number) ;
    std::cout << "reverse_number: " << reverse_number << '\n' ;

    // Substract the reversal from the original number
    const int difference = number - reverse_number ;
    std::cout << "difference: " << difference << '\n' ;

    // Finally, reverse the resulting number
    const int reverse_difference = reverse(difference) ;
    std::cout << "reverse_difference: " << reverse_difference << '\n' ;

    // Add it to its unreversed form
    const int result = difference + reverse_difference ;

    // The program will output the final result
    std::cout << "result: " << result << '\n' ;
}
Topic archived. No new replies allowed.