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 theHexspeak representation of _nif it is valid, otherwise return"ERROR".
Convert the number to uppercase hexadecimal, replace ‘0’ with ‘O’ and ‘1’ with ‘I’, and check if all characters are in the allowed set. If so, return the result; otherwise, return “ERROR”.
classSolution {
public String toHexspeak(String num) {
long n = Long.parseLong(num);
StringBuilder sb =new StringBuilder();
while (n > 0) {
int d = (int)(n % 16);
if (d == 0) sb.append('O');
elseif (d == 1) sb.append('I');
elseif (d >= 10 && d <= 15) sb.append((char)('A'+ d - 10));
elsereturn"ERROR";
n /= 16;
}
return sb.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funtoHexspeak(num: String): String {
var n = num.toLong()
val sb = StringBuilder()
while (n > 0) {
val d = (n % 16).toInt()
when (d) {
0-> sb.append('O')
1-> sb.append('I')
in10..15-> sb.append('A' + (d - 10))
else->return"ERROR" }
n /=16 }
return sb.reverse().toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deftoHexspeak(self, num: str) -> str:
n = int(num)
hexs =''while n >0:
d = n %16if d ==0:
hexs ='O'+ hexs
elif d ==1:
hexs ='I'+ hexs
elif10<= d <=15:
hexs = chr(ord('A') + d -10) + hexs
else:
return"ERROR" n //=16return hexs
structSolution;
impl Solution {
pubfnto_hexspeak(num: String) -> String {
letmut n = num.parse::<u64>().unwrap();
letmut hex = String::new();
while n >0 {
let d = n %16;
if d ==0 {
hex.push('O');
} elseif d ==1 {
hex.push('I');
} elseif d >=10&& d <=15 {
hex.push((b'A'+ (d -10) asu8) aschar);
} else {
return"ERROR".to_string();
}
n /=16;
}
hex.chars().rev().collect()
}
}