Simple (but longer Java code with explanation)


  • 0
    L
        public String toHex(int num) {
            if(num==0) {
                return String.valueOf("0");
            }                        
            StringBuilder builder = new StringBuilder();
            while(num!=0) {
                //Get last 4 bits.
                tag(builder,num&0xf);
                //Right shift the number without signs.
                num >>>= 4;
            }
            
            return builder.reverse().toString();
        }
        private void tag(StringBuilder builder, int val) {
            switch(val) {
                case 15:
                    builder.append('f');
                    break;
                case 14:
                    builder.append('e');
                    break;
                case 13:
                    builder.append('d');
                    break;
                case 12:
                    builder.append('c');
                    break;
                case 11:
                    builder.append('b');
                    break;
                case 10:
                    builder.append('a');
                    break;
                default:
                    builder.append(val);
            }
        }
    

Log in to reply
 

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