LeetCode: Reverse Integer

Previous Post

This is the previous post on same question.

Question

LeetCode Link
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Analyze

Careful about the overflow. For ruby, it’s not a problem. For c++, need more consideration.

Code

Ruby Code

# @param {Integer} x
# @return {Integer}
def reverse(x)
    sign = x >= 0 ? 1 : -1
    x = x.abs
    y = 0
    int_max = 2 ** 31 - 1
    while x > 0 do
        digit = x % 10
        y = y * 10 + digit
        if y > int_max
            y = 0
            break
        end
        x /= 10
    end
    y * sign
end

C++ Code

class Solution {
public:
    int reverse(int x) {
        int sign = 1;
        if(x < 0) {
            sign = -1;
            x = -x;
        }
        int int_max = (1 << 31) - 1; //notice the priority of << is lower than -
        int dime = int_max / 10;
        int tail = int_max % 10 + (sign == 1 ? 0 : 1);

        int y = 0;
        while(x > 0){
            int digit = x % 10;
            if(y > dime || (y == dime && digit > tail)){
                return 0;
            }
            y = y * 10 + digit;
            x /= 10;
        }
        return y * sign;
    }
};

LeetCode题目:Reverse Integer

题目让反转一个int,主要问题在于如何考虑越界问题。



Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).



代码:40ms过大集合

class Solution {
public:
    int reverse(int x) {
        int sup = 1;
        {//find the most significant bit
            int temp = x;
            while(temp /= 10) {
                sup *= 10;
            }
        }
        int sub = 10;
        int y = 0;//result
        while(sup >= sub) {
            int dsup = x / sup;
            int dsub = (x % sub) / (sub / 10);
            //cout<<dsup<<","<<dsub<<",";
            x -= sup * dsup;
            x -= (sub / 10) * dsub;
            //cout<<x<<"|";
            y += sup * dsub;
            y += (sub / 10) * dsup;

            sup /= 10;
            sub *= 10;
        }
        if (sup * 10 == sub) {
            y += x;
        }
        return y;
    }
};