Skip to content

1271. Hexspeak 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  string toHexspeak(string num) {
    const long n = stol(num);
    stringstream ss;
    ss << hex << uppercase << n;
    string ans(ss.str());

    for (char& c : ans) {
      if (c > '1' && c <= '9')
        return "ERROR";
      if (c == '0')
        c = 'O';
      else if (c == '1')
        c = 'I';
    }

    return ans;
  }
};
1
2
3
4
5
6
7
class Solution {
  public String toHexspeak(String num) {
    final long n = Long.parseLong(num);
    final String ans = Long.toHexString(n).toUpperCase().replace('1', 'I').replace('0', 'O');
    return ans.chars().anyMatch(c -> Character.isDigit(c)) ? "ERROR" : ans;
  }
}
1
2
3
4
class Solution:
  def toHexspeak(self, num: str) -> str:
    s = hex(int(num)).upper()[2:].translate(str.maketrans('01', 'OI'))
    return 'ERROR' if any(c.isdigit() for c in s) else s