Excel Sheet Column
2018-03-17
In this tutorial, we will introduce how to solve the conversion between excel sheet column name and decimal numbers problems. Leetcode [#168. Excel Sheet Column Title and #171. Excel Sheet Column Number]. These problems are easy to solve, but for such a long time, I can’t totally understand why it should be solved like the discussion page said, which makes me crazy and confused. Finally, I realized that they are actually games between different numeral systems. In the following, we will analysis the two problems in detail.
Problem Description
#171. Given a column title, return its corresponding positive integer.
#168. Given a positive integer, return its corresponding column title as appear in an Excel sheet.
Analysis of #171.
#171 is easier than #168 because you can easily find the rules through several examples. We only need to multiply each digit’s number and its corresponding significance value and sum them up.
|
|
Analysis of #168.
We can assume that this is a new kind of numeral system N1. Listing some examples, we can find that there are 2 differences between it and our familiar decimal system.
For simplicity, let’s see another similar numeral system N2, which is defined like this:
So the numbers in system N2 look likes this:
And the numbers in normal decimal system N3 look like this:
Compare N2 with N3, we can find out that, the only difference is in the last column, other columns are the same. And in the N2’s last column, ‘x’ represents ‘10’, ‘1x’ represents ‘1*10 + 10’, ‘2x’ represents ‘2*10 + 10’. The rule of converting N3’s ‘30’ to N2’s ‘2x’ is:
For other numbers which is not multiple of 10, their representations are same in N2 and N3. So we can convert N3 to N2 using the following algorithm:
We know that N1 has the similar rule with N2, the only difference is that N1 uses base 26, wheras N2 uses base 10. So we can convert N3 to N1 using similar idea.