leetcode:面试题 05.07. 配对交换(python3解法)

难度:简单

配对交换。编写程序,交换某个整数的奇数位和偶数位,尽量使用较少的指令(也就是说,位0与位1交换,位2与位3交换,以此类推)。

示例1:

复制代码
 输入:num = 2(或者0b10)
 输出 1 (或者 0b01)

示例2:

复制代码
 输入:num = 3
 输出:3

提示:

  1. num的范围在0, 2\^30 - 1之间,不会发生整数溢出。

题解:

python 复制代码
class Solution:
    def exchangeBits(self, num: int) -> int:
        if num == 1:
            return 2
        n = bin(num).split('b')[1]
        list_n = list(n)
        
        if len(n) % 2 == 1:
            list_n = ['0'] + list_n
        for i in range(0,len(list_n)-1,2):
            list_n[i],list_n[i+1] = list_n[i+1],list_n[i]
    
        return int("".join(['0b']+list_n),2)

        
相关推荐
To_OC5 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC5 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK7 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
Warson_L12 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅12 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅12 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L12 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅13 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L13 小时前
python的类&继承
python
Warson_L13 小时前
类型标注/type annotation
python