Python算法-進制轉(zhuǎn)換

168. Excel表列名稱

給你一個整數(shù) columnNumber ,返回它在 Excel 表中相對應(yīng)的列名稱。
例如:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

# 26 進制
class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = ''
        while columnNumber:
            columnNumber, y = divmod(columnNumber, 26)   # 求商、取余
            if y == 0:
                columnNumber -= 1
                y = 26
            res = chr(y + 64) + res
            # print(res)
        return res
171. Excel 表列序號

給你一個字符串 columnTitle ,表示 Excel 表格中的列名稱。返回 該列名稱對應(yīng)的列序號 。
例如:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        ret = 0
        for i in columnTitle:
            ret = ret * 26 + ord(i) - 64
        return ret
190. 顛倒二進制位

輸入:n = 00000010100101000001111010011100
輸出:964176192 (00111001011110000010100101000000)
解釋:輸入的二進制串 00000010100101000001111010011100 表示無符號整數(shù) 43261596,
因此返回 964176192,其二進制表示形式為:
00111001011110000010100101000000。

# # 列表元素反轉(zhuǎn)
class Solution:
    def reverseBits(self, n: int) -> int:
        n = '{:032b}'.format(n)    # 轉(zhuǎn)為字符串
        # print(type(n))
        n = n[::-1]
        return int(n,2)
# # 位運算
# 每次把 res 左移,把 n 的二進制末尾數(shù)字,拼接到結(jié)果 res 的末尾。然后把 n 右移。
class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for i in range(32):
            res = (res << 1) | (n & 1)
            n >>= 1
        return res
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容