美文网首页Leetcode
Leetcode 405. Convert a Number t

Leetcode 405. Convert a Number t

作者: SnailTyan | 来源:发表于2018-09-06 19:05 被阅读6次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Convert a Number to Hexadecimal

    2. Solution

    • Version 1
    class Solution {
    public:
        string toHex(int num) {
            if(num == 0) {
                return "0";
            }
            string s;
            const string HEXO = "0123456789abcdef";
            while(num != 0 && s.length() < 8) {
                s += HEXO[num & 0xf];
                num >>= 4;
            }
            reverse(s.begin(), s.end());
            return s;
        }
    };
    
    • Version 2
    class Solution {
    public:
        string toHex(int num) {
            if(num == 0) {
                return "0";
            }
            unsigned int n = num;
            string s;
            const string HEXO = "0123456789abcdef";
            while(n) {
                int remainder = n % 16;
                s += HEXO[remainder];
                n >>= 4;
            }
            reverse(s.begin(), s.end());
            return s;
        }
    };
    

    Reference

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

    相关文章

      网友评论

        本文标题:Leetcode 405. Convert a Number t

        本文链接:https://www.haomeiwen.com/subject/ibffgftx.html