
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:
- 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:
|
|
Example 2:
|
|
| 提示 | 解題應用 |
|---|---|
| BitManipulation | Hex |
Default:
|
|
解答思路:
基本上只要能將正值寫出了,負值就不是什麼大問題了,因為可以把負值當作溢位的正值,意思就是int的32位元極大值為2147483647,因為+1就會溢位但也表示2147483648等同於-2147483648,而如果在順勢向後推,4294967295也就等同於-1,再來只要以正常處理正值的處理方式,先除以16(16位元)取餘數後判斷其是否為10到15,如果是就轉為a~f,否則就直接將數字轉為字串型別,之後將結果放入回傳字串的開頭,最後原本正值除以16的商數,再拿來不斷重覆上述動作直到商數歸0為止。
程式碼解說:
首先先判斷該10進位的值是否為負數,若是則轉成一超過極大值的正數,而若為0則回傳字串”0”,接著就開始不斷將該數與16相除,若餘數大於等於10則需轉為字母,先將該餘數-10再加上97之後直接強制將其值轉為字串(ASCII),若小於10則將該數轉為該字的字串(強制轉會變ASCII),之後再把剛剛的字串放入結果開頭,最後將正數與16相除的商數賦予回去,不斷重覆上述動作直到商數歸0並回傳結果
|
|
完整程式碼:
|
|
總結:
要將10進位制數轉為16進位制時,若原數字為負數,透過溢位的方式將負數轉為一個超過極大值的正數,再來只要不斷將其值除以16取餘數,並判斷該餘數要轉字母還是保留為數字後放入結果字串的開頭,最後不斷重覆將剛剛的商數再除16取餘數並判斷,直到商數歸0為止。