Simple Java solution


  • 0
    N
    public String toHex(int num) {
            
            if(num==0)
                return "0";
                
           StringBuilder result = new StringBuilder();
           
            if(num<0){
                int base= 1;
               char[] twos = Integer.toBinaryString(num).toCharArray();    
                for(int i=0;i<twos.length;i+=4){
                    int hexValue=(twos[i]-'0')*8+(twos[i+1]-'0')*4+((twos[i+2])-'0')*2+(twos[i+3]-'0');
                     result.append(hexValue>9?(char)('a'+(hexValue-10)):(char)(hexValue+'0'));
                }
            }else{
                int rem=0;
               while(num!=0){
                   rem =num%16;
                   result.append(rem>9?(char)('a'+(rem-10)):(char)(rem+'0'));
                   num/=16;
               } 
               result.reverse();
            }
            return result.toString();
        }

Log in to reply
 

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