码迷,mamicode.com
首页 > 其他好文 > 详细

65. Reverse Integer && Palindrome Number

时间:2014-09-09 10:40:08      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   os   io   ar   strong   for   

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

 

 

65. Reverse Integer && Palindrome Number

标签:des   style   blog   http   os   io   ar   strong   for   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3961255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!