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;
  • 相关阅读:
    NLTK和Stanford NLP两个工具的安装配置
    对传统虚拟机软件的相关调研
    FasterRCNN目标检测实践纪实
    MySQL数据库远程连接的配置方案
    Windows10电脑安装macOS Mojave系统的方法(最新版系统,含超详细步骤截图)
    用Hash Table(哈希散列表)实现统计文本每个单词重复次数(频率)
    Windows10远程桌面连接配置
    dwz局部表格分页
    dwz中combox的value问题
    【转帖】C++编译原理 资料
  • 原文地址:https://www.cnblogs.com/feiling/p/3158297.html
Copyright © 2011-2022 走看看