Saturday, October 20, 2012

Mathenatics16

Q16. In Excel sheet rows are marked using integer numbers like 1,2,3 but the columns are marked using characters. Like A, B and C.
so here column 0 = A (assuming column starting with 0)
column 1 = B
column 25 = Z
column 26 = AA
column 100 = CW
Write a program to give the string representation of column for given integer.

Some test data: 

A - Z will be represented by 0-25
AA - ZZ will create 26*26 = 676 more numbers.
so AA-ZZ will be from 26 - 701
Number - Column name
701        -  ZZ
702        -  AAA
703        - AAB
[Question was asked in MS interview. Order of complexity was also asked for the code.]

Answer:

public class Mathematics16 {
    public static String convertToExcelColumn(int n) {
        if (n < 0) {
            return "";
        }

        int m = n % 26;
        StringBuilder sb = new StringBuilder();
        sb.append((char) ('A' + m));
        n/=26;

        while (n > 26) {
            m = n % 26;
            sb.insert(0, (char) ('A' + m - 1));
            n /= 26;
        }

        if (n > 0) {
            sb.insert(0, (char) ('A' + n - 1));
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 704; i++) {
            System.out.println(i + " -> " + convertToExcelColumn(i));
        }
    }
}

  • Order of complexity of above algo = number of chars in excel column  name
                                                                   = O(log26n)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.