09回文数-切片的详细应用

时间:2021-08-31
本文章向大家介绍09回文数-切片的详细应用,主要包括09回文数-切片的详细应用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

式例:

输入:x=121

输出:Ture

代码:

class Solution(object):
    def isPalindrome(self,x):
        y=str(x)
        tag=1
        len_y=len(y)
        for i in range(len_y//2):
            if y[i]!=y[len_y-1-i]:
                tag=0
        if tag:
            return True
        return False
    # 利用python中的切片操作
    '''
    python中的切片操作:
    object(start_index:end_index:step)
    start_index:起始索引
    end_index:终止索引
    step:步长
    '''
    def isPalindrome2(self,x):
        # str(x)[::-1]:步长为-1,表示从后向前切片
        tag=1 if str(x)==str(x)[::-1] else 0
        return True if tag==1 else False

solution=Solution()
y=solution.isPalindrome2(121)
print(y)

  

原文地址:https://www.cnblogs.com/xiaoqing-ing/p/15209580.html