1. 解题思路
这一题是leetcode双周赛171的第二题,同样是一个medium的题目。
这一题如果要直接找上下游最邻近的二进制回文数还挺麻烦的,反正我一下子没怎么想到思路,不过这道题可以暴力点搞定,我们直接找出所有 1 1 1到 8192 8192 8192的所有二进制回文数,然后考察给定的任意一个数与其最邻近的前后两个二进制回文数的距离即可。
2. 代码实现
给出python代码实现如下:
def get_binary_palindromes(n):
binary_palindromes = []
for i in range(1, n+1):
s = bin(i)[2:]
if s == s[::-1]:
binary_palindromes.append(i)
return binary_palindromes
binary_palindromes = get_binary_palindromes(8192)
class Solution:
def minOperations(self, nums: List[int]) -> List[int]:
def query(num):
i = bisect.bisect_left(binary_palindromes, num)
if binary_palindromes[i] == num:
return 0
return min(num-binary_palindromes[i-1], binary_palindromes[i]-num)
return [query(num) for num in nums]
提交代码评测得到:耗时27ms,占用内存18.38MB。
1538

被折叠的 条评论
为什么被折叠?



