Leetcode 3766. Minimum Operations to Make Binary Palindrome

  • [Leetcode 3766. Minimum Operations to Make Binary Palindrome](#Leetcode 3766. Minimum Operations to Make Binary Palindrome)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题是leetcode双周赛171的第二题,同样是一个medium的题目。

这一题如果要直接找上下游最邻近的二进制回文数还挺麻烦的,反正我一下子没怎么想到思路,不过这道题可以暴力点搞定,我们直接找出所有 1 1 1到 8192 8192 8192的所有二进制回文数,然后考察给定的任意一个数与其最邻近的前后两个二进制回文数的距离即可。

2. 代码实现

给出python代码实现如下:

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。

相关推荐
Espresso Macchiato2 天前
Leetcode 3781. Maximum Score After Binary Swaps
·leetcode medium·leetcode3781·leetcode双周赛172
Espresso Macchiato2 天前
Leetcode 3768. Minimum Inversion Count in Subarrays of Fixed Length
滑动窗口·leetcode hard·leetcode双周赛171·leetcode 3768
Espresso Macchiato2 天前
Leetcode 3771. Total Score of Dungeon Runs
leetcode medium·leetcode 3771·leetocde周赛479
Espresso Macchiato2 天前
Leetcode 3790. Smallest All-Ones Multiple
leetcode medium·leetcode 3790·leetcode周赛482
Espresso Macchiato21 天前
Leetcode 3767. Maximize Points After Choosing K Tasks
leetcode medium·leetcode双周赛171·leetcode 3767
Espresso Macchiato21 天前
Leetcode 3765. Complete Prime Number
leetcode medium·leetcode双周赛171·leetcode 3765
Espresso Macchiato2 个月前
Leetcode 3741. Minimum Distance Between Three Equal Elements II
滑动窗口·leetcode medium·leetcode 3741·leetcode周赛475
Espresso Macchiato3 个月前
Leetcode 3702. Longest Subsequence With Non-Zero Bitwise XOR
leetcode medium·异或操作·leetcode 3702·leetcode周赛470
Espresso Macchiato3 个月前
Leetcode 3694. Distinct Points Reachable After Substring Removal
滑动窗口·leetcode medium·leetcode双周赛166·leetcode 3694