BiruLyu
6/22/2017 - 3:39 AM

405. Convert a Number to Hexadecimal.cpp

public class Solution {
    public String toHex(int num) {
        StringBuilder res = new StringBuilder();
        char[] dict = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        while (num != 0) {
        //for (int i = 0; i < 8; i++) {
            int temp = num & 15;
            res.append(dict[temp]);
            num = num >>> 4;
        }
        return res.length() == 0 ? "0" : res.reverse().toString();
    }
}
const string HEX = "0123456789abcdef";
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        string result;
        int count = 0;
        while (num && count++ < 8) {
            result = HEX[(num & 0xf)] + result;
            num >>= 4;
        }
        return result;
    }
};