加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

letecode [405] - Convert a Number to Hexadecimal

发布时间:2020-12-13 23:46:58 所属栏目:Linux 来源:网络整理
导读:Given an integer,write an algorithm to convert it to hexadecimal. For negative integer,?two’s complement?method is used. Note: All letters in hexadecimal ( a-f ) must be in lowercase. The hexadecimal string must not contain extra leading?

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%的用户

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读