Created
February 7, 2014 08:53
-
-
Save dvliman/8859280 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write a program that converts a human readable column header into a column index. | |
// A column header is an arbitrary length string of the characters A through Z, e.g: "A", "B", "AB", "BA" or "AAK". | |
// A represents the first column and its index is 1, B is the second with an index of 2, AA is the 27th column, etc. | |
// The program should read the column header from standard in and print the result to standard out as a string of digits. | |
// Given an input string of "A" the program should output only "1". | |
// | |
// Note that you can compile and test your code in the browser multiple times before submitting. | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.HashMap; | |
public class Solution { | |
public static void main(String[] args) throws Exception { | |
try { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
String input; | |
while ((input = br.readLine()) != null) { | |
System.out.println(convert(input)); | |
} | |
} catch(IOException io) { | |
io.printStackTrace(); | |
} | |
// System.out.println(convert("A")); // #=> 1 | |
// System.out.println(convert("C")); // #=> 3 | |
// System.out.println(convert("AA")); // #=> 27 | |
// System.out.println(convert("KL")); // #=> 298 | |
} | |
public static int convert(String columnHeader) { | |
final char[] alphabets = new char[] { | |
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', | |
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', | |
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' | |
}; | |
HashMap<Character, Integer> index = new HashMap<Character, Integer>(); | |
for (int i = 1; i < alphabets.length; i++) { | |
index.put(alphabets[i - 1], i); | |
} | |
// AA = 26 * 1 + 1 | |
// AAA = 26 * 26 * 1 + 26 * 1 + 1 | |
// KL = 26 * 11 + 12 | |
int acc = 0; | |
int pos = columnHeader.length() - 1; | |
for (char each : columnHeader.toCharArray()) { | |
int mult = (int) Math.pow(26, pos); | |
acc = acc + index.get(each) * mult; | |
pos--; | |
} | |
return acc; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment