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;
    }
};

“LeetCode题目:Reverse Integer”的一个回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注