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;
  • 相关阅读:
    模块之间的消息传递优势与问题
    cp命令
    gimp的python控制台生成UI代码
    three.js(六) 地形法向量生成
    mysql 主从复制配置
    Three.js(九)perlin 2d噪音的生成
    three.js(五) 地形纹理混合
    mongodb 复制
    pycparse python的c语法分析器
    ajax出现 所需的数据还不可用
  • 原文地址:https://www.cnblogs.com/feiling/p/3158297.html
Copyright © 2011-2022 走看看