• 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:

    1. All letters in hexadecimal (a-f) must be in lowercase.
    2. 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.
    3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
    4. 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"
    

    >>> hex(123)
    '0x7b'
    >>> hex(123)[2:]
    '7b'
    >>> hex(1)
    '0x1'
    >>> hex(0)
    '0x0'
    >>> bin(0)
    '0b0'
    >>> bin(1)
    '0b1'
    class Solution(object):
        def toHex(self, num):
            """
            :type num: int
            :rtype: str
            """
            # use recurively        
            if num < 0:
                return hex(num+(1<<32))[2:]
            else:
                return hex(num)[2:]
    

     注:Main ideal is to flip the negative number to positive by using following code: # num = num + 2**32

    负数的binary 表示就是num + 2**32的正数表示。因为python里hex和bin都是针对正数有效。

    >>> bin(-1)
    '-0b1'
    >>> bin(-12)
    '-0b1100'
    >>> hex(-12)
    '-0xc'
    >>> hex(-123)
    '-0x7b'

    因此,自己写的话,可以:

    class Solution(object):
        def toHex(self, num):
            """
            :type num: int
            :rtype: str
            """
            # use recurively        
            if num == 0: return "0"            
            if num < 0:
                num += (1<<32)
            ans = ""
            hex_s = "0123456789abcdef"
            while num != 0:
                ans = hex_s[num & 0xf] + ans
                num = num >> 4
            return ans        
    

     其他解法:

    def toHex(self, num):
            if num==0: return '0'
            mp = '0123456789abcdef'  # like a map
            ans = ''
            for i in range(8):
                n = num & 15       # this means num & 1111b
                c = mp[n]          # get the hex char 
                ans = c + ans
                num = num >> 4
            return ans.lstrip('0')  #strip leading zeroes
    
  • 相关阅读:
    float、定位、inline-block、兼容性需注意的特性总结
    meta 标签 详细说明
    兼容探讨一
    javascript性能优化总结二(转载)
    javascript性能优化总结一(转载人家)
    特效合集(原生JS代码)适合初学者
    svg实现简单沙漏旋转
    SVG制作简单的图形
    SVG的简单介绍
    jQuery之效果
  • 原文地址:https://www.cnblogs.com/bonelee/p/8836737.html
Copyright © 2020-2023  润新知