Skip to content

Commit 4a132e3

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 405
1 parent 69739a9 commit 4a132e3

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@
238238
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
239239
- [394 Decode String](https://leetcode.com/problems/decode-string/description/)
240240
- [399 Evaluate Division](https://leetcode.com/problems/evaluate-division/description/)
241+
- [405 Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/)
241242
- [412 Fizz Buzz](https://leetcode.com/problems/fizz-buzz/description/)
242243
- [415 Add Strings](https://leetcode.com/problems/add-strings/description/)
243244
- [427 Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/description/)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
"""Base class for all LeetCode Problems."""
3+
4+
def toHex(self, num: int) -> str:
5+
"""
6+
Given a 32-bit integer num, return a string representing its hexadecimal
7+
representation. For negative integers, two’s complement method is used.
8+
9+
All the letters in the answer string should be lowercase characters, and there
10+
should not be any leading zeros in the answer except for the zero itself.
11+
12+
Note: You are not allowed to use any built-in library method to directly solve
13+
this problem.
14+
"""
15+
if num == 0:
16+
return "0"
17+
18+
WRAPPER = "0123456789abcdef"
19+
MASK = 0xFFFFFFFF
20+
num &= MASK
21+
22+
result = ""
23+
while num != 0:
24+
bits = num % 16
25+
result = WRAPPER[bits] + result
26+
num //= 16
27+
return result
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._405_convert_a_number_to_hexadecimal import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["num", "expected"],
8+
argvalues=[
9+
(26, "1a"),
10+
(-1, "ffffffff"),
11+
(0, "0"),
12+
],
13+
)
14+
def test_func(num: int, expected: str):
15+
"""Tests the solution of a LeetCode problem."""
16+
hex_code = Solution().toHex(num)
17+
assert hex_code == expected

0 commit comments

Comments
 (0)