clear C++ solution


  • 0
    K
    class Solution {
    public:
        string toHex(int num) {
            unsigned int n=num;
            string res="";
            while(n)
            {
                int b=n%16;
                res+=b<10?char('0'+b):char('a'+b-10);
                n/=16;
            }
            reverse(res.begin(),res.end());
            return res==""?"0":res;
        }
    };

  • 0
    H

    You can avoid reversing by simply doing this instead

    res = b<10?char('0'+b):char('a'+b-10) + res
    

  • 0

    @hitesh96db said in clear C++ solution:

    res = b<10?char('0'+b):char('a'+b-10) + res

    Every time you execute this command, it has to move all the elements in res over each time it executes. If you do 1 reverse, it only executes 1 time no matter how large the input is.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.