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:
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%的用户
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |