0ms C++ bit manipulation solution without reverse operation


  • 0
    /*
          mask     = 1111,00000000 .... 0000
          num      = 0010,10110101 .... 0000
    mask & num     = 0010,00000000 .... 0000
    (mask&num)>>28 = 0000,00000000 .... 0010
      num<<4       = 1011,0101 ....
    if( checking for first non-zero ) push_back((mask&num)>>28);
    repeat 8 times
    */
    class Solution {
    public:
    	string toHex(int num) {
    	    const string Hex = "0123456789abcdef";
    		string result;
    		unsigned mask= 15<<28;
    		for(int i=0 ; i<8 ; i++){
    			int tmp = (num & mask)>>28;
    			num <<=4;
    			if( tmp == 0 && result.empty()) continue;
    			result.push_back(Hex[tmp]);
    		}
    		if( result.empty() ) result.push_back('0');
    		return result;
    	}
    };
    

Log in to reply
 

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