c++ divided into three kinds of situations


  • 0
    D

    class Solution {
    public:
    string toHex(int num) {
    string s;
    int n;
    char h[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        if(num==0)
            return "0";
        else if(num<0)
        {
            num=(-1)*num-1;
            while(num>0)
            {
                n=num%16;
                s.push_back(h[15-n]);
                num/=16;
            }
            for(int j=s.size();j<8;j++)
                s.push_back('f');
        }
        else
        {
            while(num>0)
            {
                n=num%16;
                s.push_back(h[n]);
                num/=16;
            }
        }
        reverse(s.begin(),s.end());
        return s;
    }
    

    };


  • 0
    D

    // divided into two kinds of situations
    class Solution {
    public:
    string toHex(int num) {
    string s;
    unsigned int nu=num;
    int n;
    char h[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        if(nu==0)
            return "0";
        
        while(nu>0)
        {
            n=nu%16;
            s.push_back(h[n]);
            nu/=16;
        }
        reverse(s.begin(),s.end());
        return s;
    }
    

    };


Log in to reply
 

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