c++ with bitset


  • 0

    In the c++, the bitset can help us get num'bit no matter the num is positive or negative. Then we can convert it to hexadecimal every 4.
    For example:
    the decimal ->Binary -> Hexadecimal
    16 -> 0001 0000 -> 10

    class Solution {
    public:
        string toHex(int num) {
            if(num == 0)
    		    return "0";
        	int index,count = 0;
        	string res = "";
        	char a[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    	    bitset<32> n(num);
    		for (int i = 0; i < 32; i+=4)
    		{	
    			index = (n[i]<<0)+(n[i+1]<<1)+(n[i+2]<<2)+(n[i+3]<<3);
    			res += a[index];
    		}
        	reverse(res.begin(),res.end());
        	for (int i = 0; i < res.size(); ++i)//remove extra leading 0s.
        	{
    	    	if(res[i] == '0')
    	    		count++;
    	    	else
    	    		break;
    	    }
    	    res.erase(res.begin(),res.begin()+count);
    	    return res;
        }
    };
    

Log in to reply
 

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