3 lines Java


  • 0
    W
    private String toHex(int n) {
        StringBuilder sb = new StringBuilder();
        for (int j; n != 0; n >>>= 4) sb.append((char) ((j = n & 15) < 10 ? '0' + j : 'a' + j - 10));
        return sb.reverse().toString();
    }
    

    Another version without unnecessary reverse operation, 4 lines

    private String toHex(int n) {
        char[] chars = new char[8];
        int idx = 7;
        for (int j; n != 0; n >>>= 4) chars[idx--] = (char) ((j = n & 15) < 10 ? '0' + j : 'a' + j - 10);
        return idx == 7 ? "0" : new String(chars, ++idx, 8 - idx);
    }

Log in to reply
 

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