LeetCode Solutions

405. Convert a Number to Hexadecimal

Time: $O(\log_{16} n)$

Space: $O(1)$

			

class Solution {
 public:
  string toHex(unsigned num) {
    const vector<char> hex{'0', '1', '2', '3', '4', '5', '6', '7',
                           '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    string ans;

    while (num) {
      ans += hex[num & 0xf];
      num >>= 4;
    }

    reverse(begin(ans), end(ans));
    return ans.empty() ? "0" : ans;
  }
};
			

class Solution {
  public String toHex(int num) {
    final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    StringBuilder sb = new StringBuilder();

    while (num != 0) {
      sb.append(hex[num & 0xf]);
      num >>>= 4;
    }

    return sb.length() == 0 ? "0" : sb.reverse().toString();
  }
}