题目:
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
0
s. 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:
Input: 26 Output: "1a"
Example 2:
Input: -1 Output: "ffffffff"
链接:https://leetcode.com/problems/convert-a-number-to-hexadecimal/#/description
3/22/2017
这道题思路很简单,但是写起来有点啰嗦。
注意:
1. StringBuilder.substring()返回的是String,不是StringBuilder!
2. 判断StringBuilder的值是否是“”:ret.toString().equals("")。需要先变为String才可以
1 public class Solution { 2 public String toHex(int num) { 3 StringBuilder sb = new StringBuilder(); 4 String tmp = new String(); 5 StringBuilder ret = new StringBuilder(); 6 HashMap<String, String> lookup = new HashMap<String, String>(); 7 lookup.put("0000", "0"); 8 lookup.put("0001", "1"); 9 lookup.put("0010", "2"); 10 lookup.put("0011", "3"); 11 lookup.put("0100", "4"); 12 lookup.put("0101", "5"); 13 lookup.put("0110", "6"); 14 lookup.put("0111", "7"); 15 lookup.put("1000", "8"); 16 lookup.put("1001", "9"); 17 lookup.put("1010", "a"); 18 lookup.put("1011", "b"); 19 lookup.put("1100", "c"); 20 lookup.put("1101", "d"); 21 lookup.put("1110", "e"); 22 lookup.put("1111", "f"); 23 24 int c = 1; 25 for (int i = 0; i < 32; i++) { 26 if ((num & c) == c) sb.append('1'); 27 else sb.append('0'); 28 c <<= 1; 29 } 30 sb.reverse(); 31 boolean leading = true; 32 for (int i = 0; i < 32; i+=4) { 33 tmp = sb.substring(i, i+4); 34 if (tmp.equals("0000") && leading) continue; 35 leading = false; 36 ret.append(lookup.get(tmp)); 37 } 38 if (ret.toString().equals("")) return "0"; 39 return ret.toString(); 40 } 41 }
看别人的解法很有收获,其实不需要借用2进制变为16进制,直接用16进制的数组map就可以了,注意这时按位与也要变成和15进行
1 public class Solution { 2 3 char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 4 5 public String toHex(int num) { 6 if(num == 0) return "0"; 7 String result = ""; 8 while(num != 0){ 9 result = map[(num & 15)] + result; 10 num = (num >>> 4); 11 } 12 return result; 13 } 14 15 16 }
讨论:https://discuss.leetcode.com/category/531/convert-a-number-to-hexadecimal
看这道题想起来一个问题,经常有输入n的问题,有没有想过什么时候用从n减来计算,什么时候从start(0或1或其他)计算到n呢?