LeetCode-405. Convert a Number to Hexadecimal

来源:互联网 发布:mixer sam 软件 编辑:程序博客网 时间:2024/04/30 01:00

问题:https://leetcode.com/problems/convert-a-number-to-hexadecimal/?tab=Description
十进制转十六进制。
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 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.
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 1: Input:26 Output:”1a”
Example 2: Input:-1 Output:”ffffffff”
分析:对于num,从右边开始,每4位转化成一个16进制的数。
参考C++代码:

class Solution {public:     char* hex="0123456789abcdef";    string toHex(int num) {        return toSHex(num);    }    string toSHex(unsigned int num){        string s;        if(num>15){            unsigned int tem=num%16;            s+=hex[tem];            return toSHex(num>>4)+s;        }        else{            s+=hex[num];            return s;        }    }};
0 0
原创粉丝点击