刷题—Palindrome Number

来源:互联网 发布:手机改ip软件 编辑:程序博客网 时间:2024/05/21 14:17

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

java:

通过int转换为string,看string是否首位与相应的位相等,判断是不是palindrome

public class Solution {
    public boolean isPalindrome(int x) {
        if (x == 0) return true;
        if (x < 0) return false;
        String s = String.valueOf(x);
        int i = 0;
        int j = s.length();
        while(i<j){
            if (!s.substring(i,i+1).equals(s.substring(j-1,j))){
                return false;
            }
            i++;
            j--;
        }
        return true;
        
        
    }
}

python:

思路:把x每次都除以10,余数乘以十叠加,看是否相等。

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x<0:
            return False
        ret = 0
        abc = x
        while x>0:
            ret = ret*10 +x%10
            x = x/10
        if ret == abc:
            return True
        else:
            return False

0 0
原创粉丝点击