Leetcode - Excel Sheet Column Number (Java)
Tags: Algorithm, Java, LeetCodeGiven a column title as appear in an Excel sheet, return its corresponding column number.
For example:
|
1 2 3 4 5 6 7 |
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 |
Related to this question Excel Sheet Column Title
This is a normal number system conversion problem. Think about how we convert a binary number to a decimal number?
1101001 = 1* 2 ^6 + 1 * 2^5 ..
We can easily have the following implementation:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class ExcelColumnToNumber { int convert(String str) { char[] chs = str.toCharArray(); int j = 0; int res = 0; while( j < chs.length ) { res = res * 26 + (chs[j] - 'A' + 1); j++; } return res; } public static void main(String[] args) { System.out.println(new ExcelColumnToNumber().convert("AA")); System.out.println(new ExcelColumnToNumber().convert("BA")); System.out.println(new ExcelColumnToNumber().convert("BZ")); } } |











