my solution a sort of long but clear 0ms c++


  • 0
    H

    my solution a sort of long but clear

    class Solution {
    public:
        string toHex(int num) {
            vector<int> res(8,0);
            int n = 0;
            long long m = num;
            m = abs(m);
            string ans = "";
            int i = 0;
            while(m) {
                n = m % 16;
                res[i++] = n;
                m = m / 16;
            }
            
            if (num < 0) {
                for(int i = 0 ;i < 8 ;i++) {
                    res[i] = 15 - res[i];    
                }
                
                int i = 0;
                while((res[i] + 1) == 16) {
                   res[i] = 0;   
                   i++;
                }
                res[i] += 1;
            }
            
            reverse(res.begin(), res.end());
            int flag = 1;
            for(int i = 0; i < 8 ; i++) {
                if (res[i] == 0 && flag == 1)
                    continue;
                flag = 0;
                if (res[i] >= 10) {
                    ans += 'a' + res[i] - 10;
                } else {
                    ans += '0' + res[i];
                }
            }
            return flag == 1 ? "0" : ans;
        }
    };
    

Log in to reply
 

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