C# solution - convert to uint


  • 0
    W

    We can convert to unit and then do bit operations:

    public class Solution {
        public string ToHex(int num) {
            uint n = (uint)num;
            uint a = 0xf0000000;
            string s = null;
            bool leadingzero = true;
            for (int i = 0; i < 8; i++)
            {
                uint m = (a & n) >> ((7 - i) << 2);
                if (m != 0 || !leadingzero || i == 7)
                {
                    s += (m < 10) ? (char)('0' + m) : (char)('a' + (m - 10));
                    leadingzero = false;
                }
                a >>= 4;
            }
            return s;
        }
    }

Log in to reply
 

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