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"
.
Example 1:
Input: num = "257" Output: "IOI" Explanation: 257 is 101 in hexadecimal.
Example 2:
Input: num = "3" Output: "ERROR"
Constraints:
1 <= N <= 10^12
- There are no leading zeros in the given string.
- All answers must be in uppercase letters.
Solution: Simulation
Time complexity: O(logn)
Space complexity: O(logn)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: string toHexspeak(string num) { long n = stol(num); string ans; while (n) { int r = n % 16; char c; if (r == 0) c = 'O'; else if (r == 1) c = 'I'; else if (r >= 10 && r <= 15) c = 'A' + r - 10; else return "ERROR"; ans += c; n >>= 4; } reverse(begin(ans), end(ans)); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment