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!
        }
    };
    
  • 相关阅读:
    Python实现MapReduce,wordcount实例,MapReduce实现两表的Join
    structure needs cleaning
    Lifecycle of an ASP.NET MVC 5 Application
    ASP.NET Integration with IIS 7
    Execution order of modules in IIS7
    Assembly Binding redirect: How and Why?
    Cannot See Worker Processes Icon in IIS
    What is the main difference between a key, an IV and a nonce?
    核心玩法的三要素
    ruby各种循环输出数组元素
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3961255.html
Copyright © 2011-2022 走看看