405. Convert a Number to Hexadecimal【E】【leetcode】

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"

Subscribe to see which companies asked this question


最下面的是不要臉版本,當然了,太不要臉了,所以呢,只需要自己實現一下hex這個函數就行

怎麼實現呢,那就是一個循環,不斷地除以16,然後轉化成十六進制就行了


class Solution(object):
    def toHex(self, num):
        def change(num):
            res = ''
            hex = ['a','b','c','d','e','f']
            for i in num[::-1]:
                #print i
                if i > 9:
                    res += hex[i%10]
                else:
                    res += str(i)
            return res


        def f(num):
            #print '```'
            res = []
            while num > 0:
                #print num
                res += num % 16,
                num /= 16
                #print num
            return  res

        if num == 0:
            return '0'
        if num < 0:
            num += (1 << 32)
        res = f(num)
        #print res
        return change(res)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章