Generate the hexadecimal representation for a given non-negative integer number as a string. The hex representation should start with "0x".

There should not be extra zeros on the left side.

Examples

0's hex representation is "0x0"

255's hex representation is "0xFF"

Assumption: not negative.

Approach: mod calculate each time, if the remainder > 10. we map it to the char. until the number = 0.

public class Solution{
    public String hex(int number) {
        String prefix = "0X";
        StringBuilder sb = new StringBuilder();
        if (number == 0) {
            return prefix + '0';
        }
        while (number > 0) {
            rem = number % 16;
            if (rem < 10) {
                sb.append((char)('0' + rem));
            } else {
                sb.append((char)('A' + rem - 10));
            }
            number = number / 16;
        }
        return prefix + sb.reverse().toString();
    }
}

results matching ""

    No results matching ""