目录
今天第一次做leetcode上面的题,选了一道easy型的判断回文数,但这第一道题完成的太艰难了,代码能写出来,可是第一次用,那个上面规则和格式挺麻烦,我在spyder上运行没问题,在leetcode上面就是通不过,一顿修改,一个小时就这么没有了,但最终还是过了,挺高兴的,以后做程序员吗?我也不知道,大概率不会,但是喜欢编程,就坚持下去吧。另外,看了一些评论区,竟然有人用一行代码解决了,我直接哭死。
题解
1.
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up totarget
.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
def TwoSum():
nums=[4,2,6,1,9,5]
target=15
length=len(nums)-1
for i in range(length):
for j in range(i,length):
if nums[i]+nums[j]==target:
return [i,j]
break
else:
continue
print(TwoSum())
输出结果
[2, 4]
9.Given an integer
x
, returntrue
ifx
is palindrome integer.An integer is a palindrome when it reads the same backward as forward.
解析:根据题目描述和给出的示例,首先确定回文数是一个非负数,比如-121反过来是121-就不行,然后就想办法把对称位置的数进行比较。
spyder运行代码
def ispalindrome(x):
t = len(x)
L = list(x)
if int(x)<0:
print('False')
elif t%2==0:
for i in range(t):
if i<=t//2-1:
if L[i]==L[t-1-i]:
continue
else:
print('False')
break
else:
print('True')
break
else:
for i in range(t):
if i<=(t-1)//2-1:
if L[i]==L[t-1-i]:
continue
else:
print('False')
break
else:
print('True')
break
x = input('please input a integer:')
ispalindrome(x)
注 代码已进行测试,就不再写输出结果了
Leetcode代码
class Solution:
def isPalindrome(self, x: int) -> bool:
t = len(str(x))
L = list(str(x))
if int(x)<0:
return False
elif t%2==0:
for i in range(t):
if i<=t//2-1:
if L[i]==L[t-1-i]:
continue
else:
return False
break
else:
return True
break
else:
for i in range(t):
if i<=(t-1)//2-1:
if L[i]==L[t-1-i]:
continue
else:
return False
break
else:
return True
break
Runtime: 130 ms, faster than 11.73% of Python3 online submissions for Palindrome Number.
Memory Usage: 13.9 MB, less than 62.46% of Python3 online submissions for Palindrome Number.
这time。。。革命尚未成功,同志仍需努力啊