Skip to content

Commit d5c5cea

Browse files
authored
Create convert-a-number-to-hexadecimal.cpp
1 parent 6dcc01b commit d5c5cea

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string toHex(int num) {
7+
if (!num) {
8+
return "0";
9+
}
10+
11+
string result;
12+
while (num && result.length() != sizeof(int) * 2) {
13+
int hex = num & 15;
14+
if (hex < 10) {
15+
result.push_back('0' + hex);
16+
} else {
17+
result.push_back('a' + hex - 10);
18+
}
19+
num >>= 4;
20+
}
21+
reverse(result.begin(), result.end());
22+
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)