算法设计与应用基础-第三周

    xiaoxiao2021-03-25  65

    (1)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:

    All letters in hexadecimal (a-f) must be in lowercase.The hexadecimal string must not contain extra leading0s. 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 useany method provided by the library which converts/formats the number to hex directly. 分三类情况讨论,在讨论小于零的情况时,转化为大于零的整数来转换为十六进制数。 #include <string> class Solution { public: string toHex(int num) { char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if(num==0) return "0"; else if(num>0) { string res; while(num>0) { int remind=num; num=num/16; if(remind<10) { char c = hex[remind]; res += c; } else { char c = hex[remind]; res += c; } } reverse(res.begin(),res.end()); return res; } else if(num<0) { string res; num=(-1)*num-1; while(num>0) { int remind=num; char c = remind+'0'; if(remind<10) { char c = hex[15-remind]; res += c; } else { char c = hex[15-remind]; res += c; } num/=16; } for(int j=res.size();j<8;j++) res.push_back('f'); reverse(res.begin(),res.end()); return res; } } };
    转载请注明原文地址: https://ju.6miu.com/read-37566.html

    最新回复(0)