[LeetCode] Hexspeak

1271. Hexspeak

A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and only if it consists only of the letters in the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}.

Given a string num representing a decimal integer n, return the Hexspeak representation of n if it is valid, otherwise return "ERROR".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
string toHexspeak(string num) {
long long x = stoll(num);
if(!x) return "O";
unordered_map<int, char> mp;
mp[1] = 'I';
mp[0] = 'O';
mp[10] = 'A';
mp[11] = 'B';
mp[12] = 'C';
mp[13] = 'D';
mp[14] = 'E';
mp[15] = 'F';
string res = "";
while(x) {
long long r = x % 16;
x /= 16;
if(!mp.count(r)) return "ERROR";
res.push_back(mp[r]);
}
reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/14/PS/LeetCode/hexspeak/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.