807 回文数
描述
判断一个非负整数 n 的二进制表示是否为回文数
我们保证 0 <= n <= 2^32 - 1
样例
样例1
输入: n = 0
输出: True
解释:
0 的二进制表示为:0。
样例2
输入: n = 3
输出: True
解释:
3 的二进制表示为:11。
样例3
输入: n = 4
输出: False
解释:
4 的二进制表示为:100。
样例4
输入: n = 6
输出: False
解释:
6 的二进制表示为:110。
题解
class Solution:
"""
@param n: non-negative integer n.
@return: return whether a binary representation of a non-negative integer n is a palindrome.
"""
def is_palindrome(self, n: int) -> bool:
# Write your code here
a=bin(n)[2:]
for i in range (1,len(a)):
if a[i-1]!=a[-i]:
return False
else:
return True
310 数字变形
描述
现在题目给出一个字符串数字A。
字符串数字B是A的变形,由字符串数字A的位数交替形成。
依次为A的右数第一位数,左数第一位数,右数第二位数…以此类推,得到字符串数字B。
0<=A<=1e200
样例
输入: “12345678”
输出:“81726354”
题解:
class Solution:
"""
@param a: the integer discrible in problem
@return: the integer after distortion
"""
def distortion(self, a: str) -> str:
#
nstr=''
for i in range (1,len(a)//2+1):
nstr+=a[-i]+a[i-1]
if len(a)%2==1:
nstr+=a[len(a)//2]
return nstr
1334 旋转数组
描述
给定一个数组,将数组向右移动k步,其中k为非负数。
样例
样例 1:
输入: [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转1步: [7,1,2,3,4,5,6]
向右旋转2步: [6,7,1,2,3,4,5]
向右旋转3步: [5,6,7,1,2,3,4]
样例 2:
输入: [-1,-100,3,99], k = 2
输出: [3,99,-1,-100]
解释:
向右旋转1步: [99,-1,-100,3]
向右旋转2步: [3,99,-1,-100]
from typing import (
List,
)
class Solution:
"""
@param nums: an array
@param k: an integer
@return: rotate the array to the right by k steps
"""
def rotate(self, nums: List[int], k: int) -> List[int]:
# Write your code here
n=len(nums)
nnums=nums[n-k:n]+nums[0:n-k]
return nnums
五一小长假结束了,算法题还是得多练!