LeetCode OJ 405. Convert a Number to Hexadecimal

20 篇文章 0 订阅
1 篇文章 0 订阅

LeetCode OJ 405. Convert a Number to Hexadecimal


Description

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example1

Input:
26

Output:
“1a”

Example2

Input:
-1

Output:
“ffffffff”

解题思路

首先想到的处理方法就是对数进行位操作(bit manipulation)。要转换为16进制数,那么每次处理的就是低位的4bit,要取到低位的4bit可以用&操作得到,然后对取到的数进行判断,从而转换为‘0’~‘9’字符或‘a’~‘f’字符加入到结果字符串的末尾,然后将原来的数字右移四位。执行循环,直到正数变为0或者负数显示到32bit。

Note:

负数在计算机内部采用2的补码形式来存储,就是每一个二进制位都取反,得到的结果再加1。这样我们在处理负数时直接右移4bit时就可以了。(其实一开始也没注意到这一点,所以一开始是将负数转换为正数进行处理,后来才想起来计算机中负数的存储方式。)但是我们需要做一个限制:32bit,不然会产生死循环。

代码

个人github代码链接


class Solution {
public:
    string toHex(int num) {
        if(num == 0)
            return "0";
        string ans = "";
        int bit = 8;
        while (num && bit) {
            int tmp = num & 15;
            if (tmp < 10)
                ans = to_string(tmp) + ans;
            else
                ans = (char)('a' + tmp - 10) + ans;
            num = num >> 4;
            bit--;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值