7/5 每日一題(將數字轉換為16進制)
Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Example 1:
Input: num = 26 Output: "1a"
Example 2:
Input: num = -1 Output: "ffffffff"
Constraints:
-231 <= num <= 231 - 1
class Solution:
def __init__(self):
self.dict={
0:'0',
1:'1',
2:'2',
3:'3',
4:'4',
5:'5',
6:'6',
7:'7',
8:'8',
9:'9',
10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f'
}
def toHex(self, num: int) -> str:
res=[] #初始化
#處理負數
if num == 0:
return self.dict[num]
if num < 0:
num += 16 ** 8 #轉換成正數
while num >= 1 :
s=num%16
num //= 16 #繼續計算下一位
n=self.dict[s] #轉換16進制
res.insert(0,n) #從個位數開始計算
num_str=''.join(res)
return num_str
-------------------------參考解答 位元運算
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁