Question #38808

write a class called reverse to reverse an unsigned integer.by using only while,do while and for statments.for example,8602 should be written as 2068 by using util.h.

Expert's answer

#include <iostream>
using namespace std;
class reverse
{
public:
    static int reverse_while(int n)
    {
        int sign = n > 0 ? 1 : -1;
        int inv = 0;
        n = n * sign;
        while (n > 0)
        {
            inv = inv * 10 + (n % 10);
            n /= 10;
        }
        return inv * sign;
    }
    static int reverse_do_while(int n)
    {
        int sign = n > 0 ? 1 : -1;
        int inv = 0;
        n = n * sign;
        do
        {
            inv = inv * 10 + (n % 10);
            n /= 10;
        } while (n > 0);
        return inv * sign;
    }
    static int reverse_for(int n)
    {
        int sign = n > 0 ? 1 : -1;
        int inv = 0;
        n = n * sign;
        for (; n > 0; n /= 10)
        {
            inv = inv * 10 + (n % 10);
        }
        return inv * sign;
    }
};
int main(int argc, char* argv[])
{
    int n;
    cout << "input number:" << endl;
    cin >> n;
    cout << "reverse using:" << endl;
    cout << "\twhile : " << reverse::reverse_while(n) << endl;
    cout << "\tdo while: " << reverse::reverse_do_while(n) << endl;
    cout << "\tfor : " << reverse::reverse_for(n) << endl;
    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS