Pages

Saturday, January 9, 2010

Excel column number

PROBLEM: Write a function (with helper functions if needed) called to Excel that takes an excel column value (A,B,C,D…AA,AB,AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=27..).

SOLUTION: This solution is one based (that means A will be 1 and not 0 "zero" ).
package google;

public class ExcelColumnNumber {
    public int findColumnNumber(String s) {
        int base = 26, result = 0, digit = 0;
        for (int i = 0; i < s.length(); i++) {
            digit = s.charAt(i) - 'A' + 1;
            result = base * result + digit;
        }
        return result;
    }
}


TEST:
package google.test;

import google.ExcelColumnNumber;

import java.util.Random;

public class ExcelColumnNumberTest {
    public static void main(String[] args) {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        final int TEST_SIZE = 10000;
        final int STRING_SIZE = 5; //no more than 5
        ExcelColumnNumber excelNumber = new ExcelColumnNumber();
        for (int j = 0; j < TEST_SIZE; j++) {
            String string = "";
            for (int i = 0; i <= random.nextInt(STRING_SIZE); i++) {
                string += (str.charAt(random.nextInt(26)));
            }
            System.out.println("Column: " + string + " Number: "
                    + excelNumber.findColumnNumber(string));
        }
    }
}

No comments :