进阶之路

首页 新随笔 管理

Reverse Integer

Reverse digits of an integer.

Example1: x =  123, return  321 Example2: x = -123, return -321

click to show spoilers.

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).

思路: 注意符号,溢出。

class Solution {
public:
    int reverse(int x) {
        int tag = 1;
        if(x < 0){
            tag = -1;
            x *= -1;
        }
        int k = 0, y = 0;
        while(x > 0){
            y = y * 10 + (x % 10);
            x /= 10;
        }
        if(y < 0) printf("Overflow!\n");
        return (y * tag);
    }
};

 

Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

思路: 注意负数和溢出情况都是 false. 其余情况,就是反转再判断,参考上题.

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0) return false;
        int v = x, y = 0;
        while(v > 0){
            y = y * 10 + (v % 10);
            v /= 10;
        }
        if(y == x) return true;
        return false; // 注意:溢出时,也肯定是 false!
    }
};

 

 

posted on 2014-09-08 12:13  进阶之路  阅读(175)  评论(0编辑  收藏  举报