zoukankan      html  css  js  c++  java
  • 65. Reverse Integer && Palindrome Number

    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!
    ");
            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!
        }
    };
    
  • 相关阅读:
    设置导航栏标题颜色及字体大小
    FMDB的简单实用
    iPhone越狱
    P1122 最大子树和
    UVA11090 Going in Cycle!!
    P1156 垃圾陷阱
    P1325 雷达安装
    P1038 神经网络
    P2922 [USACO08DEC]秘密消息Secret Message
    P2292 [HNOI2004]L语言
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3961255.html
Copyright © 2011-2022 走看看