題目
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”
題意
就是輸入10進位的數字轉成16進位
解法
這在python中通常也是一行就解決了,而且高階語言通常不會處理這種問題
hex(num_decimal)
但在C語言中很有趣,還有bit的解法,容我細細說來,按照一般方案就是一直取餘數,最後再把答案顛倒過來就好了,如果不懂怎麼算的可以參考這個影片1,底下是用C++實現的代碼,需要注意的小細節有幾個地方
- 1.要注意負數的情況,因此使用unsigned來解決這問題
- 2.可以利用str+num 自動轉為str的技巧來解題
- 3.最後把儲存的字串反轉過來就是答案了
class Solution { public: string toHex(unsigned int num) { if (num==0) return "0"; int res; string ans; while(num>0){ res= num%16; if (res<10) ans+='0'+res; else ans+='a'+(res%10); num=num/16; } reverse(ans.begin(),ans.end()); return ans; } };
最令我訝異的是還有用bit解題的,複習了我很久以前的位元概念,這對底層要非常的熟,需要知道int 是一個4byte的組成,因此為32bit,轉成16位元就是每4個bit換成一個字元,例如1010 ,十進位表示為10,轉成16進位後為字元a表示,由於只要取最後4個位元而已,因此要使用一個mask對輸入做&的動作,而mask設為10進位的15就是2進位的1111
num = 26
0001’1010
&—-1111
=—-1010
之後就一直往右位移4個位元,然後重複的轉成16進位表示,因為int為32位元,因此總共要移動8次(32/4),一直重複執行到8次移動完畢就解完答案了,寫完這題真的是收穫良多,也複習了C很底層的技術,需要注意的點為(num!=0)要寫在迴圈中,因為若是解到左邊都是0的話那就不需要再解碼了,直接輸出答案就是了
class Solution { public: string toHex(unsigned int num) { if (num==0) return "0"; // The given number is guaranteed to fit within the range of a 32-bit signed integer. // So 32/4 = 8 segments int seg=8; // 15's binary is '1111'. It can be used to select the right-most 4 bits. int mask=15; // Pre-define a string mapping the index value with the hex value string hex="0123456789abcdef"; string ans=""; // Keep doing until all 32 bits are iterated or the input number is zero. while((seg>0)and (num!=0)){ ans.push_back(hex[mask&num]); num = num>>4; seg-=1; } int last=ans.length()-1; for(int i=0;i<ans.length()/2;i++){ swap(ans[i],ans[last]); last-=1; } return ans; } };
另外,給出原作者[2]所提供的python解答
class Solution: def toHex(self, num: int) -> str: # Pre-define a string mapping the index value with the hex value myhex = "0123456789abcdef" # The given number is guaranteed to fit within the range of a 32-bit signed integer. # So 32/4 = 8 segments seg = 8 mask = 15 # 15's binary is '1111'. It can be used to select the right-most 4 bits. mystr = "" if num == 0: return '0' while (seg>0) and (num!=0): # Keep doing until all 32 bits are iterated or the input number is zero. mystr = ''.join((myhex[num&mask], mystr)) num = num >> 4 seg -= 1 return mystr
參考資料
1.https://www.youtube.com/watch?v=QJW6qnfhC70&t=725s&ab_channel=TheOrganicChemistryTutor
2.https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/904682/Python-3-Bit-manipulation-99.87-wcomments
3.https://www.youtube.com/watch?v=KXwRt7og0gI&ab_channel=TheCherno