LeetCode#405 Convert a Number to Hexadecimal

問題描述

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  • All letters in hexadecimal (a-f) must be in lowercase.
  • The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  • The given number is guaranteed to fit within the range of a 32-bit signed integer.
  • You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:26

Output:"1a"

Example 2:

Input:-1

Output:"ffffffff"

補充說明:

一個老生長談的問題,給定一個十進制整數(shù),輸出它的十六進制形式。這里有幾點要求,其一是輸出的字符均為小寫,其二是如果十六進制的高位為0,那么不顯示多余的0,其三是這個數(shù)字是一個32位整形,其四是不能用轉(zhuǎn)換或者格式化的庫。

方案分析

  1. ok,很清晰,正數(shù)用除數(shù)取余處理。負數(shù)處理成正數(shù)再去處理。
  2. 負數(shù)如何處理?這里說了,最大是32位整數(shù),那么就加一個32位的最大值就ok了。

python實現(xiàn)

def toHex(self, num):
    ret = ''
    map = ('0', '1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')
    if num == 0:
        return '0'
    if num < 0:
        num += 2**32
    while num > 0 :
        num, val = divmod(num, 16)
        ret += map[val]
    return ret[::-1]

方案分析2

  1. 處理數(shù)字問題,不用位操作簡直毀天滅地。4bits表示一個數(shù)字,按照2進制處理唄。
  2. 別人的代碼。

python實現(xiàn)2

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0: return '0'
        ret = ''
        map = ['a', 'b', 'c', 'd', 'e', 'f']

        # 32 bit == 4 byte each x char represents 4 bits, half a byte
        for i in xrange(8): # at max we have 32 bit integer, so 8 iterations of computing 4 bits in each iteration == 32 bits
            cur = num & 0b1111 # get least significant 4 bits, this corresponds to least significant hex char
            char = cur if cur < 10 else map[cur - 10] # fetch hex char
            ret = str(char) + ret # append hex char to return
            num = num >> 4 # erase the 4 bits we just computed for next iteration

        pos = 0
        while pos < len(ret) and ret[pos] == '0':
            pos += 1

        return ret[pos:]
最后編輯于
?著作權(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)容