C# solution


  • 0
    K
    public class Solution {
        public string ToHex(int num) {
            long n = 0;
    
            if (num < 0)
                n = (long)Math.Pow(2,32) + num;
            else
                n = num;
                
            return ConvertPositive(n);
        }
        
        public string ConvertPositive(long num)
        {
            string[] arr = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
            long up = 0;
            for (int i=0;up<=num;i++)
                up = (long)Math.Pow(16,i);
            up = up/16;
            string s = String.Empty;
            long r = num;
            while (up>15)
            {
                long d = r/up;
                r = r%up;
                s = s+arr[d];
                up = up/16;
            }
            return s+arr[r];
        }
    }
    

Log in to reply
 

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