clueless coding // TODO: be smarter

LeetCode 405. Convert a Number to Hexadecimal: Java Solution

Problem Statement

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

All letters in your hexadecimal representation should be lowercase.

Do not output a hexadecimal representation with leading 0s.

If the input is 0, represent it with a single ‘0’.

You can assume that the input is a signed 32 bit integer.

Do not perform the conversion automatically with built-in standard libaries or functions.

Function Signature (JAVA):
  String toHex(int num)

  num = 27


  num = -1


TL;DR Code Solution

char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

public String toHex(int num) {

    if(num == 0) return "0";
    String result = "";

    while(num != 0){
        result = map[(num & 15)] + result;
        num = (num >>> 4);

    return result;