Skip to content

Latest commit

 

History

History

1271

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 <= num.length <= 12
  • num does not contain leading zeros.
  • num represents an integer in the range [1, 1012].

Companies:
Virtu Financial

Related Topics:
Math, String

Solution 1.

// OJ: https://leetcode.com/problems/hexspeak/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    string toHexspeak(string n) {
        stringstream ss;
        ss << uppercase << hex << stoll(n);
        string ans = ss.str();
        for (char &c : ans) {
            if (c == '0') c = 'O';
            else if (c == '1') c = 'I';
            else if (isdigit(c)) return "ERROR";
        }
        return ans;
    }
};