LeetCode[405] Convert a Number to Hexadecimal

来源:互联网 发布:智能手机看书软件 编辑:程序博客网 时间:2024/06/05 00:13

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.

Example 1:

Input:26Output:"1a"

Example 2:

Input:-1Output:"ffffffff"

不用管这个数字十进制是什么,用二进制转换为十六进制。

注意负数的情况右移位是要用符号位‘1’来补的,所以永远都不会到0,于是用一个cnt来记录移位次数(int 32bit,最多移次)

class Solution {public:string toHex(int num) {string hex = "0123456789abcdef";string ans = "";int cnt = 0;while (num != 0 && cnt++ < 8) {ans.push_back(hex[num & 15]);num >>= 4;}reverse(ans.begin(), ans.end());if (ans.empty()) {ans = "0";}return ans;}};

0 0