zoukankan      html  css  js  c++  java
  • 9. Palindrome Number

    题目链接:

    https://leetcode.com/problems/palindrome-number/

    一开始的做法是转化为字符串,然后对字符串进行操作,简单方便,但效率低。

     1 public boolean isPalindrome(int x) {
     2     if(x < 0)
     3         return false;
     4     String str = String.valueOf(x);
     5     byte[] bStr = str.getBytes();
     6     int size = str.length();
     7     for(int i = 0; i < (size+1) / 2; i ++) {
     8         int j = size - 1 - i;
     9         if(bStr[i] != bStr[j]) 
    10             return false;
    11     }
    12     return true;

    而下面方法是只对数字进行操作,效率上会高很多,不过会遇到几个问题,比如:100021等。

     1 bool isPalindrome(int x) {  
     2   if (x < 0) return false;  
     3   int div = 1;  
     4   while (x / div >= 10) {  
     5     div *= 10;  
     6   }          
     7   while (x != 0) {  
     8     int l = x / div;  
     9     int r = x % 10;  
    10     if (l != r) return false;  
    11     x = (x % div) / 10;  
    12     div /= 100;  
    13   }  
    14   return true;  
    15 }  
  • 相关阅读:
    Java异常处理和设计
    一次qps测试实践
    Alternate Task UVA
    Just Another Problem UVA
    Lattice Point or Not UVA
    Play with Floor and Ceil UVA
    Exploring Pyramids UVALive
    Cheerleaders UVA
    Triangle Counting UVA
    Square Numbers UVA
  • 原文地址:https://www.cnblogs.com/yuan2016/p/6112722.html
Copyright © 2011-2022 走看看