2018-05-29 405. Convert a Number to Hexadecimal

题意:将一个十进制数转换为16进制数。
解题思路:
方法一:常规方法,对该十进制数判断正负,正数就是十进制数直接转化为十六进制数,负数就是先变为正数然后求补码转换为十六进制数。
该方法比较麻烦。

class Solution {
public:
    string toHex(int num) {
        if(num == 0x80000000) return "80000000";
        if(num == 0) return "0";
        int flg = 0;
        if(num < 0) flg = -1;
        num = abs(num);
        string h_num;
        while(num){
            int m = num % 16;
            if(m < 10)
                h_num = char(m + '0') + h_num;
            else
                h_num = char(m - 10 + 'a') + h_num;
            num /= 16;
        }
        if(flg == -1){
            int i;
            for(i = 0; i < h_num.size(); i++){
                int m;
                if('0' <= h_num[i] && h_num[i] <= '9')
                    m = 15 - (h_num[i] - '0');
                else
                    m = 15 - (10 + (h_num[i] - 'a'));
                if(m < 10)
                    h_num[i] = char(m + '0');
                else
                    h_num[i] = char(m - 10 + 'a');
            }
            while(i < 8){
                h_num = "f" + h_num;
                i++;
            }
            h_num[7]++;
            if(h_num[7] == '9' + 1)
                h_num[7] = 'a';
            else if(h_num[7] == 'g'){
                int tmp = 1, i = 7;
                while(tmp){
                    h_num[i--] = '0';
                    h_num[i]++;
                    if(h_num[i] == '9' + 1)
                        h_num[i] = 'a';
                    else if(h_num[i] == 'g')
                        continue;
                    tmp = 0;
                }
            }
        }
        return h_num;
    }
};

方法二:对该十进制数每四位对十六进制数的f求与,这样可以得到该数的低4位数的值,然后将该值转换为十六进制数,然后将该数右移4位。由于对于正数,右移时最高位补0,对于负数右移时最高位补1,所以要判断右移的次数,最多不能超过8次。

class Solution {
public:
    string toHex(int num) {
        if(num == 0) return "0";
        string HEX = "0123456789abcdef";
        string ans;
        int count = 0;
        while(num && count++ < 8){
            ans = HEX[num & 0xf] + ans;
            num >>= 4;
        }
        return ans;
    }
};

你可能感兴趣的:(2018-05-29 405. Convert a Number to Hexadecimal)