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)

        
相关推荐
BK贝壳4 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon8 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw8 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn9 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern0911 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_9679801112 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
民乐团扒谱机14 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T14 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
databook14 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析