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;
  • 相关阅读:
    分布式缓存重建并发冲突和zookeeper分布式锁解决方案
    C# Datatable、DataReader等转化json
    OpenResty部署nginx及nginx+lua
    zookeeper+kafka集群的安装
    缓存数据生产服务的工作流程
    实现缓存与数据库双写一致性保障
    eclipse不提示问题
    Redis 多级缓存架构和数据库与缓存双写不一致问题
    代码这样写更优雅(Python版)
    java string.getBytes(“UTF-8”) javascript equivalent
  • 原文地址:https://www.cnblogs.com/feiling/p/3158297.html
Copyright © 2011-2022 走看看