进制转换题目总结

//十进制转26进制: 
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 
public class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while(n > 0) {
            n--;
            char ch = (char)(n % 26 + 'A');
            sb.append(ch);
            n = n / 26;
        }
        sb.reverse();
        return sb.toString();
    }
}
//26进制转10进制: 
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
public class Solution {
    public int titleToNumber(String s) {
        int res = 0;
        int power = 0;
        int n = s.length() - 1;
        for (int i = n; i >=0; i--) {
            int digit = s.charAt(i) - 'A' + 1;
            res += digit * Math.pow(26, power);
            power++;
        }
        return res;
    }
}
//十六进制转十进制:

//十进制转十六进制: 
public class Solution {
    public String toHex(int num) {
        if (num == 0) return "0";
        char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuilder sb = new StringBuilder();
        while( num != 0) {
            sb.append(hex[num & 15]);
            num = num >>> 4;
        } 
        sb.reverse();
        return sb.toString();
    }
}

//Roman to Integer
public class Solution {
    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        char[] array = s.toCharArray();
        char base = array[array.length - 1]; // get the last char
        int res = map.get(base);
        for (int i = array.length - 2; i >= 0; i--) {
            if (map.get(base) <= map.get(array[i])) {
                res += map.get(array[i]);
            } else {
                res -= map.get(array[i]);
            }
            base = array[i];
        }
        return res;
    }
}

// Integer to Roman TODO
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s