美文网首页
LeetCode#405 Convert a Number to

LeetCode#405 Convert a Number to

作者: 如烟花非花 | 来源:发表于2016-11-24 10:02 被阅读143次

    问题描述

    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"

    补充说明:

    一个老生长谈的问题,给定一个十进制整数,输出它的十六进制形式。这里有几点要求,其一是输出的字符均为小写,其二是如果十六进制的高位为0,那么不显示多余的0,其三是这个数字是一个32位整形,其四是不能用转换或者格式化的库。

    方案分析

    1. ok,很清晰,正数用除数取余处理。负数处理成正数再去处理。
    2. 负数如何处理?这里说了,最大是32位整数,那么就加一个32位的最大值就ok了。

    python实现

    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. 处理数字问题,不用位操作简直毁天灭地。4bits表示一个数字,按照2进制处理呗。
    2. 别人的代码。

    python实现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:]
    

    相关文章

      网友评论

          本文标题:LeetCode#405 Convert a Number to

          本文链接:https://www.haomeiwen.com/subject/icdbpttx.html