Java arithmetic solution


  • 1
    A
    public class Solution {
        public String toHex(int num) {
            if (num == 0) return "0";
            
            char[] d2h = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            
            StringBuilder res = new StringBuilder();
            
            long l = num;
            if (l < 0)
                l = (1L<<32)+l;
            
            while (l != 0) {
                res.append(d2h[(int)(l % 16)]);
                l /= 16;
            }
            
            return res.reverse().toString();
        }
    }
    

Log in to reply
 

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