Wednesday, 12 July 2017

7 Reverse Integer

Problem: Reverse digits of an integer.
Example1: x = 123, return 321

Example2: x = -123, return -321

Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Approach: Just reverse the number with reversed number stored into a long variable to accommodate overflow if occurred. Return 0 in case of overflow else return the reversed result.

class Solution {
public:
    int reverse(int x) {
        //to accomodate overflowed reversed value if occured
        long revX = 0;
        while (x != 0) {
            revX = revX * 10 + x % 10;
            //overflow check
            if (revX > INT_MAX || revX < INT_MIN) {
                return 0;
            }
            x /= 10;
        }
        return (int) revX;
    }
};

Here is the link to the ideone solution : http://ideone.com/3RwjWu
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive