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;
  • 相关阅读:
    通过代码去执行testNG用例
    启动jenkins服务错误
    linux 添加用户到sudo中
    通过jenkins API去build一个job
    iptables
    比较git commit 两个版本之间次数
    linux awk命令详解
    cron和crontab
    工作随笔——CentOS6.4支持rz sz操作
    Jenkins进阶系列之——15Maven获取Jenkins的Subversion的版本号
  • 原文地址:https://www.cnblogs.com/feiling/p/3158297.html
Copyright © 2011-2022 走看看