Java straightforward solution: ten->binary->hex


  • 0
    H
        public String toHex(int num) {
            
            // edge case
            if (num == 0)
                return "0";
                
            int[] bits = new int[32];
            
            // generate table ten->hex
            char[] tab = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            
            // convert ten->binary
            for (int i = 0; i < 32; i++) {
                
                if (((1 << i) & num) != 0) {
                    bits[i] = 1;
                } 
            }
            
            // convert binary->hex
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                int ten = 0;
                for (int j = 0; j < 4; j++) {
                    ten += (1 << j) *bits[i*4+j];
                }
                
                sb.insert(0, tab.get(ten));
            }
    
    
            // trim 0
            int start = 0;
            while (sb.charAt(start) == '0')
                start++;
    
            return sb.substring(start).toString();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.