3ms C++ solution


  • 0
    class Solution {
    public:
        string toHex(int num) {
    		string c[] = {"a","b","c","d","e","f"};
    		unsigned number;
    		if(num==0){
    		    return "0";
    		}
            if(num < 0){
                number = unsigned(~((-1)*num)) + 1;
            } else {
    			number = num;
    		}
            string r = "";
            while(number){
                int n = number % 16;
                number = number / 16;
                if(n<10){
                    char number_str[10];
                    sprintf(number_str, "%d", n);
                    r = string(number_str + r);
                }else{
                    r = string(c[n-10] + r);
                }
            }
            return r;
        }
    };
    

Log in to reply
 

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