返回介绍

solution / 1200-1299 / 1271.Hexspeak / README_EN

发布于 2024-06-17 01:03:21 字数 3636 浏览 0 评论 0 收藏 0

1271. Hexspeak

中文文档

Description

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].

Solutions

Solution 1: Simulation

Convert the number to a hexadecimal string, then traverse the string, convert the number $0$ to the letter $O$, and the number $1$ to the letter $I$. Finally, check whether the converted string is valid.

The time complexity is $O(\log n)$, where $n$ is the size of the decimal number represented by $num$.

class Solution:
  def toHexspeak(self, num: str) -> str:
    s = set('ABCDEFIO')
    t = hex(int(num))[2:].upper().replace('0', 'O').replace('1', 'I')
    return t if all(c in s for c in t) else 'ERROR'
class Solution {
  private static final Set<Character> S = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'I', 'O');

  public String toHexspeak(String num) {
    String t
      = Long.toHexString(Long.valueOf(num)).toUpperCase().replace("0", "O").replace("1", "I");
    for (char c : t.toCharArray()) {
      if (!S.contains(c)) {
        return "ERROR";
      }
    }
    return t;
  }
}
class Solution {
public:
  string toHexspeak(string num) {
    stringstream ss;
    ss << hex << stol(num);
    string t = ss.str();
    for (int i = 0; i < t.size(); ++i) {
      if (t[i] >= '2' && t[i] <= '9') return "ERROR";
      if (t[i] == '0')
        t[i] = 'O';
      else if (t[i] == '1')
        t[i] = 'I';
      else
        t[i] = t[i] - 32;
    }
    return t;
  }
};
func toHexspeak(num string) string {
  x, _ := strconv.Atoi(num)
  t := strings.ToUpper(fmt.Sprintf("%x", x))
  t = strings.ReplaceAll(t, "0", "O")
  t = strings.ReplaceAll(t, "1", "I")
  for _, c := range t {
    if c >= '2' && c <= '9' {
      return "ERROR"
    }
  }
  return t
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文