Skip to content

Commit 859fa0e

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.7 MB (59.97%)
1 parent 486ab21 commit 859fa0e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">two&rsquo;s complement</a> method is used.</p>
2+
3+
<p>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.</p>
4+
5+
<p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<pre><strong>Input:</strong> num = 26
10+
<strong>Output:</strong> "1a"
11+
</pre><p><strong class="example">Example 2:</strong></p>
12+
<pre><strong>Input:</strong> num = -1
13+
<strong>Output:</strong> "ffffffff"
14+
</pre>
15+
<p>&nbsp;</p>
16+
<p><strong>Constraints:</strong></p>
17+
18+
<ul>
19+
<li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>
20+
</ul>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def toHex(self, num: int) -> str:
3+
if num == 0:
4+
return "0"
5+
chars = "0123456789abcdef"
6+
result = []
7+
8+
for i in range(7, -1, -1):
9+
val = (num >> (4 * i)) & 0xF
10+
if val != 0 or result:
11+
result.append(chars[val])
12+
13+
return "".join(result)

0 commit comments

Comments
 (0)