Question #62867

write a function, reverseDigit, that takes an integer as a parameter and returns the number with its digits reversed. for example; the value of reverseDigit(12345) is 54321; the value of reverseDigit(5600) is 65; the value of reverseDigit(7008) is 8007; the value of reverseDigit(-532) is -235.
1

Expert's answer

2016-10-24T07:35:28-0400

Answer on Question #62867 - Programming & Computer Science - C++

Question 62867:

Write a function, reverseDigit, that takes an integer as a parameter and returns the number with its digits reversed. For example, the value of reverseDigit(12345) is 54321; the value of reverseDigit(5600) is 65; the value of reverseDigit(7008) is 8007; the value of reverseDigit(-532) is -235.

Answer:

/* This function takes an integer as a parameter and returns the number with its
* digits reversed. If no valid conversion could be performed, it returns '1' with
* the sign reversed. */
static int reverseDigit(const int value = 20)
{
    int result = 0;
    bool positive = true, error = false;
    positive = (value >= 0) ? true : false;
    if (value == INT_MIN)
    /* '-value' is underlined */
    error = true;
    int num = (positive) ? value : -value;
    while (num != 0 && !error)
    {
        int dig = num % 10;
        if (result > 0 && (INT_MAX - dig) / 10 < result)
        /* handle 'result' overflow */
        error = true;
        else
            result = result * 10 + dig;
        num /= 10;
    }
    if (error)
        result = (positive) ? -1 : 1;
    else if (!positive)
        result = -result;
    return result;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS