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.
You must not use any method provided by the library which converts/formats the number to hex directly.

Example:

Example 1:

Input:
26

Output:
"1a"
Example 2:

Input:
-1

Output:
"ffffffff"

Link:

https://leetcode.com/problems/convert-a-number-to-hexadecimal/#/description

解题方法:

先建立一个10进制转换16进制的对照表。
把int转换为二进制,每4位可以代表一位16进制,只需把每4位的2进制转换为10进制,再通过对照表就可以知道每一位对应的16进制是多少。

Tips:

转换为二进制再转换为十进制的好处是不用考虑负数的情况,因为二进制会自动转换为补码。

Time Complexity:

O(logN)

完整代码:

string toHex(int num) 
    {
        if(num == 0)
            return "0";
        string table = "0123456789abcdef";
        string ans;
        for(int i = 0; i < 8 && num != 0; i++) //每次右移4位  当num为0时停止,防止前面出现0
        {
            int sum = 0;
            for(int j = 3; j >= 0; j--) //每4位2进制可以构成一位16进制  
            {
                sum *= 2;
                if((num >> j) & 1)
                    sum += 1;
            }
            ans = table[sum] + ans;  //从字符串的头部开始加字符,后期不用反转
            num >>= 4;
        }
        return ans;     
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 做为一个咖啡喝了十年,又吸收极差的体质,本人骨质疏松,脚趾骨一踢就折,夜间腿脚乱踹,下楼膝盖酸损,今日暂且...
    曼陀珠阅读 2,166评论 0 1
  • 周六,外出。中途遇雨,不大,走了一段,看见不远处的地面上铺了一层绯红的花瓣,那是紫薇,儿时为数不多的几种花之一,很...
    小杰小西阅读 1,722评论 0 0
  • 【富士X-E2后续机型或被命名为X-E2s/X-E3】有消息称,富士X-E2的后续机型可能会被命名为X-E2s或X...
    相机Beta阅读 2,444评论 0 0