C++_3ms_Accepted (A little bit of trivial but easy to understand)


  • 0
     class Solution {
     public:
     string toHex(int num) {
        vector<char> hex = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a','b','c','d','e','f'};
        int sign = 1;
        long nums = num;
        if(num < 0){
            sign = -1;
            nums = nums * -1;
        }
        
        string res = "";
        int rem = 0;
        int di = 0;
        while(nums > 0){
            di = nums/16;
            rem = nums%16;
            res = hex[rem] + res;
            nums = di;
        }
        if(sign == -1){
            int add = 0;
            
            if(isdigit(res[res.size() - 1])){
                int comp = 15 - (res[res.size() - 1] - '0') + 1;
                res[res.size() - 1] = hex[comp % 16];
                add = comp/16;
            }else{
                int comp = 15 - ((res[res.size() - 1] - 'a') + 10) + 1;
                res[res.size() - 1] = hex[comp % 16];
                add = comp/16;
            }
            
            for(int i = res.size()-2; i >= 0; i--){
                if(isdigit(res[i])){
                    int comp = 15 - (res[i] - '0') + add;
                    res[i] = hex[comp % 16];
                    add = comp/16;
                }else{
                    int comp = 15 - ((res[i] - 'a') + 10) + add;
                    res[i] = hex[comp % 16];
                    add = comp/16;
                }
            }
            
            while(add != 0){
                res = res + hex[add%16];
                add = add/16;
            }
            
            while(res.size() < 8){
                res = 'f' + res;
            }
        }
        return res == "" ? "0" : res;
    }
    };

Log in to reply
 

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