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 Macchiato25 天前
Leetcode 3741. Minimum Distance Between Three Equal Elements II
滑动窗口·leetcode medium·leetcode 3741·leetcode周赛475
Espresso Macchiato2 个月前
Leetcode 3702. Longest Subsequence With Non-Zero Bitwise XOR
leetcode medium·异或操作·leetcode 3702·leetcode周赛470
Espresso Macchiato2 个月前
Leetcode 3694. Distinct Points Reachable After Substring Removal
滑动窗口·leetcode medium·leetcode双周赛166·leetcode 3694
Espresso Macchiato2 个月前
Leetcode 3698. Split Array With Minimum Difference
leetcode medium·分类讨论·leetcode周赛469·leetcode 3698
Espresso Macchiato3 个月前
Leetcode 3665. Twisted Mirror Path Count
动态规划·leetcode medium·leetcode 3665·leetcode双周赛164
Espresso Macchiato3 个月前
Leetcode 3669. Balanced K-Factor Decomposition
动态规划·质因数分解·leetcode medium·leetcode 3669·leetcode周赛465
Espresso Macchiato4 个月前
Leetcode 3644. Maximum K to Sort a Permutation
leetcode medium·位操作·数组排序·leetcode 3644·leetcode周赛462
Espresso Macchiato4 个月前
Leetcode 3629. Minimum Jumps to Reach End via Prime Teleportation
bfs·广度优先遍历·leetcode medium·leetcode 3629·leetcode周赛460·质数求解·质因素分解
Espresso Macchiato6 个月前
Leetcode 3572. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
leetcode medium·leetcode 3572