|
26 | 26 | <p> </p>
|
27 | 27 | <p><strong>Follow up:</strong> Could you solve it without using any built-in library method?</p>
|
28 | 28 |
|
29 |
| - |
30 | 29 | ## Solutions
|
31 | 30 |
|
32 | 31 | <!-- tabs:start -->
|
33 | 32 |
|
34 | 33 | ### **Python3**
|
35 | 34 |
|
36 | 35 | ```python
|
37 |
| - |
| 36 | +class Solution: |
| 37 | + def toHex(self, num: int) -> str: |
| 38 | + if num == 0: |
| 39 | + return '0' |
| 40 | + chars = '0123456789abcdef' |
| 41 | + s = [] |
| 42 | + for i in range(7, -1, -1): |
| 43 | + x = (num >> (4 * i)) & 0xf |
| 44 | + if s or x != 0: |
| 45 | + s.append(chars[x]) |
| 46 | + return ''.join(s) |
38 | 47 | ```
|
39 | 48 |
|
40 | 49 | ### **Java**
|
41 | 50 |
|
42 | 51 | ```java
|
| 52 | +class Solution { |
| 53 | + public String toHex(int num) { |
| 54 | + if (num == 0) { |
| 55 | + return "0"; |
| 56 | + } |
| 57 | + StringBuilder sb = new StringBuilder(); |
| 58 | + while (num != 0) { |
| 59 | + int x = num & 15; |
| 60 | + if (x < 10) { |
| 61 | + sb.append(x); |
| 62 | + } else { |
| 63 | + sb.append((char) (x - 10 + 'a')); |
| 64 | + } |
| 65 | + num >>>= 4; |
| 66 | + } |
| 67 | + return sb.reverse().toString(); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +```java |
| 73 | +class Solution { |
| 74 | + public String toHex(int num) { |
| 75 | + if (num == 0) { |
| 76 | + return "0"; |
| 77 | + } |
| 78 | + StringBuilder sb = new StringBuilder(); |
| 79 | + for (int i = 7; i >= 0; --i) { |
| 80 | + int x = (num >> (4 * i)) & 0xf; |
| 81 | + if (sb.length() > 0 || x != 0) { |
| 82 | + char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); |
| 83 | + sb.append(c); |
| 84 | + } |
| 85 | + } |
| 86 | + return sb.toString(); |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +### **C++** |
| 92 | + |
| 93 | +```cpp |
| 94 | +class Solution { |
| 95 | +public: |
| 96 | + string toHex(int num) { |
| 97 | + if (num == 0) return "0"; |
| 98 | + string s = ""; |
| 99 | + for (int i = 7; i >= 0; --i) |
| 100 | + { |
| 101 | + int x = (num >> (4 * i)) & 0xf; |
| 102 | + if (s.size() > 0 || x != 0) |
| 103 | + { |
| 104 | + char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); |
| 105 | + s += c; |
| 106 | + } |
| 107 | + } |
| 108 | + return s; |
| 109 | + } |
| 110 | +}; |
| 111 | +``` |
43 | 112 |
|
| 113 | +### **Go** |
| 114 | +
|
| 115 | +```go |
| 116 | +func toHex(num int) string { |
| 117 | + if num == 0 { |
| 118 | + return "0" |
| 119 | + } |
| 120 | + sb := &strings.Builder{} |
| 121 | + for i := 7; i >= 0; i-- { |
| 122 | + x := num >> (4 * i) & 0xf |
| 123 | + if x > 0 || sb.Len() > 0 { |
| 124 | + var c byte |
| 125 | + if x < 10 { |
| 126 | + c = '0' + byte(x) |
| 127 | + } else { |
| 128 | + c = 'a' + byte(x-10) |
| 129 | + } |
| 130 | + sb.WriteByte(c) |
| 131 | + } |
| 132 | + } |
| 133 | + return sb.String() |
| 134 | +} |
44 | 135 | ```
|
45 | 136 |
|
46 | 137 | ### **...**
|
|
0 commit comments