zoukankan      html  css  js  c++  java
  • Leetcode: Palindrome Numbers

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

    尝试用两头分别比较的方法,结果发现无法解决1000021这种问题

     1 public class Solution {
     2     public boolean isPalindrome(int x) {
     3         if(x<0) return false;
     4         int lastbit=x%10;
     5         int firstbit;
     6         int num=x;
     7         int bits=0;
     8         while(num/10!=0){
     9             num=num/10;
    10             bits++;
    11         }
    12         firstbit=num;
    13         if(firstbit!=lastbit) return false;
    14         else{
    15             x=x-firstbit*((int)(Math.pow(10,bits)));
    16             x=x/10;
    17             if(x==0) return true;
    18             else return isPalindrome(x);
    19         }
    20     }
    21 }

    查看了论坛的解答,看到一个很好的solution, 它怎么想到13行的 div/=100的,给跪了,这样刚好解决了中间有0的问题,比如1021会被判定为false, 而121会被判定为true。 解答详见:http://leetcode.com/2012/01/palindrome-number.html

     1 public class Solution {
     2     public boolean isPalindrome(int x) {
     3         if (x < 0) return false;
     4         int div = 1;
     5         while (x / div >= 10) {
     6             div *= 10;
     7         }        
     8         while (x != 0) {
     9             int l = x / div;
    10             int r = x % 10;
    11             if (l != r) return false;
    12             x = (x % div) / 10;
    13             div /= 100;
    14         }
    15         return true;
    16     }
    17 }

  • 相关阅读:
    Js Array 删除
    语音播报功能
    js实现HashTable
    Js 克隆
    获取电脑名和IP地址
    获取电脑名和Ip
    IIS 配置问题
    WCF 服务
    【并查集】wikioi1001舒适的路线
    【实用】读取信息
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3710668.html
Copyright © 2011-2022 走看看