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"
.
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.
Rust Solution
struct Solution;
#[allow(clippy::wrong_self_convention)]
impl Solution {
fn to_hexspeak(num: String) -> String {
let x: i64 = num.parse::<i64>().unwrap();
let s = format!("{:X}", x);
let mut res: Vec<char> = vec![];
for c in s.chars() {
match c {
'0' => res.push('O'),
'1' => res.push('I'),
c @ 'A'..='F' => res.push(c),
_ => return "ERROR".to_string(),
}
}
res.iter().collect()
}
}
#[test]
fn test() {
let num = "257".to_string();
let res = "IOI".to_string();
assert_eq!(Solution::to_hexspeak(num), res);
let num = "3".to_string();
let res = "ERROR".to_string();
assert_eq!(Solution::to_hexspeak(num), res);
let num = "619879596177".to_string();
let res = "ERROR".to_string();
assert_eq!(Solution::to_hexspeak(num), res);
}
Having problems with this solution? Click here to submit an issue on github.