zoukankan      html  css  js  c++  java
  • leetcode -- Palindrome Number

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

    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.

    方法1.将输入reverse下,看结果与输入是否相等,但是Reverse后的数可能溢出

     1 public class Solution {
     2     public boolean isPalindrome(int x) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(x < 0) return false;
     6         
     7         int reverseX = reverseNum(x);
     8         
     9         if(x == reverseX)
    10             return true;
    11         else
    12             return false;
    13         
    14     }
    15     
    16     public int reverseNum(int x){
    17         boolean positive = (x > 0) ? true : false;
    18         int result = 0;
    19         x = Math.abs(x);
    20         while(x > 0){
    21             result = result * 10 + x % 10;
    22             x = x / 10;
    23         }
    24         if(!positive){
    25             result *= -1;
    26         }
    27         return result;
    28     }
    29 }
    View Code

     方法2.不断比较最高位与最低位,如果相等去除最高位和最低位,直到x = 0

     1 public class Solution {
     2     public boolean isPalindrome(int x) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(x < 0) return false;
     6         
     7         int tmp = x;
     8         int s = 1;
     9         boolean flag = true;
    10         while(tmp / 10 > 0){
    11             s *= 10;
    12             tmp = tmp / 10;
    13         }
    14         
    15         while(x > 0){
    16             int quotient = x / s;
    17             int remainder = x % 10;
    18             if(quotient != remainder){
    19                 flag = false;
    20                 break;
    21             }
    22             
    23             x = x - quotient * s;
    24             x = x - remainder;
    25             x = x / 10;
    26             s = s / 100;
    27         }
    28         return flag;
    29     }
    30     
    31 }
    View Code

     方法2中代码23-25行重构如下

    1 x = x % s /10;
  • 相关阅读:
    js--事件
    js之table操作
    2019年目标
    history.back返回后输入框值丢失问题
    C++ 工程师养成 每日一题4.5 (迭代器遍历)
    C++ 工程师养成 每日一题fourth (reverse的使用)
    C++ 工程师养成 每日一题third (子数列排序)
    C++工程师养成 每日一题(string使用)
    C++工程师养成 每日一题(vector使用)
    运算符优先级
  • 原文地址:https://www.cnblogs.com/feiling/p/3158297.html
Copyright © 2011-2022 走看看