zoukankan      html  css  js  c++  java
  • 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.
    class Solution {
       public String toHexspeak(String num) {
            long n = Long.parseLong(num);
            String res = Long.toHexString(n).toUpperCase().replace('1', 'I').replace('0', 'O');
            for (char c : res.toCharArray())
                if (Character.isDigit(c))
                    return "ERROR";
            return res;        
        }
    }
    class Solution {
        public String toHexspeak(String num) {
            
            long n = Long.parseLong(num);
            HashMap<Integer, Character> map = new HashMap<>();
            map.put(0, 'O');
            map.put(1, 'I');
            map.put(10, 'A');
            map.put(11, 'B');
            map.put(12, 'C');
            map.put(13, 'D');
            map.put(14, 'E');
            map.put(15, 'F');
            
            String ans = "";
            
            while(n > 0){
                int rem = (int)(n % 16);
                if(rem > 1 && rem < 10) return "ERROR";
                n = n / 16;
                ans = map.get(rem) + ans;
            }
            
            return ans;
            
        }
    }
  • 相关阅读:
    git学习笔记
    angular自定义指令-1
    转 三范式
    CentOS 7 安装NVIDIA驱动实现修改分辨率和扩屏功能
    acm 2034
    acm 2031
    记票统计
    acm 2020 map 逆向输出
    acm 2014
    将输入的字符一个一个读入
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11968524.html
Copyright © 2011-2022 走看看