1. 程式人生 > 其它 >[LeetCode] 405. Convert a Number to Hexadecimal

[LeetCode] 405. Convert a Number to Hexadecimal

Given an integernum, returna string representing its hexadecimal representation. For negative integers,two’s complementmethod 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

數字轉換為十六進位制數。

給定一個整數,編寫一個演算法將這個數轉換為十六進位制數。對於負整數,我們通常使用補碼運算方法。

注意:

十六進位制中所有字母(a-f)都必須是小寫。
十六進位制字串中不能包含多餘的前導零。如果要轉化的數為0,那麼以單個字元'0'來表示;對於其他情況,十六進位制字串中的第一個字元將不會是0字元。
給定的數確保在32位有符號整數範圍內。
不能使用任何由庫提供的將數字直接轉換或格式化為十六進位制的方法。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

這道題考察的是計算機基礎。注意給定的 input 數字的範圍是在 Integer 範圍內,所以這裡一開始我先把 input 數字轉換成 long 型避免越界。之後,對於每一位的處理,也是像處理二進位制數字一樣。什麼意思呢?如果你想知道某個十進位制數字的二進位制表達,在 Java 中你需要將數字的最低位和1做AND操作,並右移一位,直到這個數字為 0。轉譯成十六進位制也是一樣,但是這裡我們需要一個 map,也是不斷地將 num 的最低位去和 15 做 AND 操作(因為十六進位制是從0到15),直到 num == 0。每次我們無符號右移 4 個位置,這是十六進位制的表達。

時間O(c) - 應該是一個常數時間,取決於最後十六進位制數字的長度

空間O(c)- 應該是一個常數時間,取決於最後十六進位制數字的長度

Java實現

 1 class Solution {
 2     char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 3 
 4     public String toHex(int num) {
 5         // corner case
 6         if (num == 0) {
 7             return "0";
 8         }
 9 
10         // normal case
11         String res = "";
12         while (num != 0) {
13             // res = map[(num & 0xF)] + res;
14             res = map[(num & 15)] + res;
15             num = (num >>> 4);
16         }
17         return res;
18     }
19 }

LeetCode 題目總結