Convert number to base three

Convert number to base three

Problem :

Represent a given numbers in following format   : (with base 3 )

1 = “1”
2 = “2”
3 = “00”
4 = “01”
5 = “02”
6 = “10”
7 = “11”
8 = “12”
09 = “20”
10 = “21”
11 = “22”
12 = “000”
13 = “001”
14 = “002”
15 = “010”
Problem is not that simple as it looks . Its like a trinary number instead of a binary number.

Solution in java :

/**
 * Subtract powers of 3 incrementally till number cannot be further subtracted from.
 * Left-pad remaining number with count of numbers subtracted.
 */
private String convert(int num) {
        int strLen = 0;
        for (int i = 1; i < 1000; i++) {
            double pow = Math.pow(3, i);
            if (num – pow >= 0) {
                num -= pow;
                strLen += 1;
            } else {
                break;
            }
        }
        return createStringRepresentation(num, strLen);
    }
    private String createStringRepresentation(int num, int strLen) {
        String numStr = Integer.toString(num, 3);
        return lpad(numStr, strLen + 1);
    }
    private static String lpad(String text, int size) {
        StringBuilder builder = new StringBuilder();
        while (builder.length() < size – text.length()) {
            builder.append(‘0’);
        }
        return builder.toString() + text;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *