Leetcode - Convert a Number to Hexadecimal

My code:

public class Solution {
    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        String[] strs = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        int[] bits = new int[32];
        int base = 1;
        for (int i = 31; i >= 0; i--) {
            if ((num & base) != 0) {
                bits[i] = 1;
            }
            base <<= 1;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 7; i >= 0; i--) {
            int bit = 1;
            int sum = 0;
            sum += bit * bits[i * 4 + 3];
            bit <<= 1;
            sum += bit * bits[i * 4 + 2];
            bit <<= 1;
            sum += bit * bits[i * 4 + 1];
            bit <<= 1;
            sum += bit * bits[i * 4 + 0];
            sb.append(strs[sum]);
        }
        
        String ret = sb.reverse().toString();
        int start = 0;
        while (start < ret.length()) {
            if (ret.charAt(start) != '0') {
                break;
            }
            start++;
        }
        
        return ret.substring(start);
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        String ret = test.toHex(26);
        System.out.println(ret);
    }
}

reference:
https://discuss.leetcode.com/topic/62880/java-straightforward-solution-ten-binary-hex

看了答案会做的。记住,用 base = 1 进行逐位比较的时候,判断条件是:
** (num & base) != 0 **

Anyway, Good luck, Richardo! -- 10/14/2016

你可能感兴趣的:(Leetcode - Convert a Number to Hexadecimal)