C++ easy to understand toHex


  • 0
        string toHex(int num) {
            if(num==0) return "0";
            unordered_map<int,char>m({{10,'a'},{11,'b'},{12,'c'},{13,'d'},{14,'e'},{15,'f'}});
            string hex="";
            int digit=0;
            while(num&&digit<8){
                int n=num&0xf;
                num>>=4;
                char c=n>=10?m[n]:'0'+n;
                hex.push_back(c);
                digit++;
            }
            reverse(hex.begin(),hex.end());
            return hex;
        }
    

Log in to reply
 

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