Java solution without bit manipulation


  • 1
    Y

    Don't know how to add space
    public class Solution {
    public String toHex(int num) {
    StringBuilder sb=new StringBuilder();
    boolean neg=false;
    if(num==0) return "0";
    if(num<0){
    neg=true;
    if(num==Integer.MIN_VALUE) return "80000000";
    else num=0-num-1;
    }
    while(num>0){
    int mod=num%16;
    if(mod<10){
    sb.append(mod);
    }
    else {
    char c=(char)('a'+(mod-10));
    sb.append(c);
    }
    num=(num-mod)/16;
    }
    if(neg){
    String s=sb.reverse().toString();
    sb=new StringBuilder();
    for(int i=s.length()-1;i>=0;i--){
    char c=s.charAt(i);
    if(Character.isDigit(c)){
    int mod='9'-c+6;
    if(mod<10){
    sb.append(mod);
    }
    else {
    c=(char)('a'+(mod-10));
    sb.append(c);
    }
    }
    else sb.append('f'-c);
    }
    for(int i=0;i<8-s.length();i++){
    sb.append('f');
    }
    }
    return sb.reverse().toString();
    }
    }


Log in to reply
 

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