p12 判断一个数是否为回文数 (leetcode 9)

一:解题思路

二:完整代码示例 (C++版和Java版)

第一种方法C++

  //Time:O(m),Space:O(1)
  class Solution 
  {
  public:
      bool isPalindrome(int x) 
      {
          string str = to_string(x);//C++11特有语法,将整数x转化为字符串

          int i = 0, j = str.size() - 1;

          while (i < j)
          {
              if (str[i] != str[j]) return false;

              i++;
              j--;
          }
          return true;
      }
  };

第一种方法Java:

class Solution
{
    public boolean isPalindrome(int x)
    {
          String str=String.valueOf(x);

          int i=0,j=str.length()-1;
          
          while(i<j)
          {
              if(str.charAt(i)!=str.charAt(j)) return false;
              
              i++;
              j--;
          }

          return true;
    }
}

第二种方法C++:

  class Solution 
  {
  public:
      bool isPalindrome(int x) 
      {
          if (x < 0) return false;
          int temp = x;
          long y = 0;

          while (temp != 0)
          {
              int num = temp % 10;
              y = y * 10 + num;
              temp = temp / 10;
          }

          return (x==y);
      }
  };

第二种方法 Java:

class Solution
{
    public boolean isPalindrome(int x)
    {
        if(x<0) return false;
        
        int temp=x;
        long y=0;

        while(temp!=0)
        {
            int num=temp%10;
            y=y*10+num;
            temp=temp/10;
        }

        return (y==x);
    }
}

 

python 方法一:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        string = str(x)
        i=0
        j= len(string)-1
        while i<j:
            if string[i] != string[j]:return False
            i=i+1
            j=j-1

        return True

 

Python 方法二:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:return False
        temp = x
        y=0
        
        while temp!=0:
            num=temp%10
            y=y*10 + num
            temp=temp//10
        return y==x

 

posted @ 2020-03-09 21:50  repinkply  阅读(131)  评论(0)    收藏  举报