Skip to content

Commit 1ad239c

Browse files
authored
Refactor toHex function to accept int and use unsigned
1 parent 552deaf commit 1ad239c

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

  • solutions/405. Convert a Number to Hexadecimal

solutions/405. Convert a Number to Hexadecimal/405.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
class Solution {
22
public:
3-
string toHex(unsigned num) {
4-
if (num == 0)
3+
string toHex(int num) {
4+
unsigned unsignedNum = static_cast<unsigned>(num);
5+
if (unsignedNum == 0)
56
return "0";
67

78
constexpr char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',
89
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
910
string ans;
1011

11-
while (num != 0) {
12-
ans += hex[num & 0xf];
13-
num >>= 4;
12+
while (unsignedNum != 0) {
13+
ans += hex[unsignedNum & 0xf];
14+
unsignedNum >>= 4;
1415
}
1516

1617
ranges::reverse(ans);

0 commit comments

Comments
 (0)