Sunday, April 25, 2021

405. Convert a Number to Hexadecimal

 Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

 

Example 1:

Input: num = 26
Output: "1a"

Example 2:

Input: num = -1
Output: "ffffffff"

 

Constraints:

  • -231 <= num <= 231 - 1

class Solution {
public:
    string helper(int num) {
        string ans;
        string mp = "0123456789abcdef";
        while (num != 0) {
            int temp = num & 15;
            ans = mp[temp] + ans;
            num >>= 4;
            // Negative number would end up in num being zero.
            // Hence check the length.
            if(ans.size()==8) {
                break;
            }
        }
        return ans;
    }
    string toHex(int num) {
        if (num == 0) {
            return "0";
        } else {
            return helper(num);
        }
        
    }
};

No comments:

Post a Comment