letecode [405] - Convert a Number to Hexadecimal

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:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"

题目大意

  输入一个整数,输出它的16进制值。

理  解:

  取余16计算每个位的值。对于负数,用补码进行计算,转换为unsigned int型。

代 码 C++:

class Solution {
public:
    string toHex(int num) {
        if(num==0)
            return "0";
        unsigned int x;
        x = (unsigned int)num;
        string str = "";
        while(x){
            if(x%16>9){
                str = (char)(x%16 + 87) + str;
            }
            else{
                str = to_string(x%16) + str;
            }
            x /= 16;
        }
        return str;
    }
};

运行结果:

  执行用时 :4 ms, 在所有 C++ 提交中击败了90.84%的用户
  内存消耗 :8.4 MB, 在所有 C++ 提交中击败了68.06%的用户
posted @ 2019-06-21 20:09  lpomeloz  阅读(87)  评论(0编辑  收藏  举报